题目:
Sort a linked list using insertion sort.
1->3->2->5->4
1->2->3->4->5
思路:
当cur指针指向2时,pre指针从helper指针开始一直遍历到指向1时停止,pre指针指向1,此时要将2插入到1与3中间,cur.next = pre.next, pre.next = cur, cur = next
解法:
public ListNode insertionSortList(ListNode head) {
if(head == null)
return null;
ListNode helper = new ListNode(0);
ListNode pre = helper;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
pre = helper;
while(pre.next != null && pre.next.val <= cur.val){
pre = pre.next;
}
cur.next = pre.next;
pre.next = cur;
cur = next;
}
return helper.next;
}
测试代码:
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
n1.next = n3;
n3.next = n2;
n2.next = n5;
n5.next = n4;
InsertionSortList insertionSortList = new InsertionSortList();
ListNode head = insertionSortList.insertionSortList(n1);
while(head != null){
System.out.print(head.val + " ");
head = head.next;
}
}