Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //40ms
- class Solution {
- public ListNode insertionSortList(ListNode head) {
- if(head == null) return head;
- ListNode ans = head;
- head = head.next;
- ans.next = null;
- int i = 0;
- while(head != null) {
- if(head.val <= ans.val) {
- ListNode temp = head.next;
- head.next = ans;
- ans = head;
- head = temp;
- } else {
- ListNode curr = ans.next, prev = ans;//Reset the pointers to begin of ans list after each insertion
- while(curr != null && head.val >= curr.val) {
- prev = curr;
- curr = curr.next;
- }
- prev.next = head;
- ListNode temp = head.next;
- head.next = curr;
- head = temp;
- }
- }
- return ans;
- }
- }
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
Add Comment
Please, Sign In to add comment