Insertion Sort List

Sort a linked list using insertion sort.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode insertionSortList(ListNode head) {
  11. ListNode curr = head, next = null;
  12. ListNode l = new ListNode(0);
  13. while (curr != null) {
  14. next = curr.next;
  15. ListNode p = l;
  16. while (p.next != null && p.next.val < curr.val) {
  17. p = p.next;
  18. }
  19. curr.next = p.next;
  20. p.next = curr;
  21. curr = next;
  22. }
  23. return l.next;
  24. }
  25. }