Guest User

Untitled

a guest
Jun 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. //40ms
  2. class Solution {
  3. public ListNode insertionSortList(ListNode head) {
  4. if(head == null) return head;
  5. ListNode ans = head;
  6. head = head.next;
  7. ans.next = null;
  8. int i = 0;
  9. while(head != null) {
  10. if(head.val <= ans.val) {
  11. ListNode temp = head.next;
  12. head.next = ans;
  13. ans = head;
  14. head = temp;
  15.  
  16. } else {
  17. ListNode curr = ans.next, prev = ans;//Reset the pointers to begin of ans list after each insertion
  18. while(curr != null && head.val >= curr.val) {
  19. prev = curr;
  20. curr = curr.next;
  21. }
  22. prev.next = head;
  23. ListNode temp = head.next;
  24. head.next = curr;
  25. head = temp;
  26. }
  27. }
  28. return ans;
  29. }
  30. }
  31. /**
  32. * Definition for singly-linked list.
  33. * public class ListNode {
  34. * int val;
  35. * ListNode next;
  36. * ListNode(int x) { val = x; }
  37. * }
  38. */
Add Comment
Please, Sign In to add comment