Sort List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
// curr用来遍历所有node,pre用来标记linkedlist的开头
ListNode curr = head, pre = dummy;
while (curr != null && curr.next != null) {
if (curr.val <= curr.next.val) {
curr = curr.next;
} else {
pre = dummy; // 重置pre的位置
ListNode temp = curr.next; // 用来标记需要移动的node
curr.next = temp.next;
// 把pre移动到需要插入位置的前一位
while (pre.next.val <= temp.val) {
pre = pre.next;
}
// 把temp连接上
temp.next = pre.next;
pre.next = temp;
}
}
return dummy.next;
}
}Last updated