题目
Sort a linked list using insertion sort.
代码
public class Solution
{
//Definition for singly-linked list.
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
//思路:
//将待排序的链表节点依次插入到已排序链表的适当位置。
//定义以下几个变量:
//1. rtn: 指向已排序链表的头,注意在整个的插入排序过程中它是不变量;
//2. cur: 指向待排序链表中即将要插入到已排序链表的当前节点;
//3. pre: 在rtn指向的链表中,cur节点插入位置的前驱,注意pre在每次迭代前始终指向rtn(已排序链表头),迭代过程中要不断向前找到cur插入的位置
//4. next: 指向待排序链表中即将要插入到已排序链表的下一个节点;
public ListNode InsertionSortList(ListNode head)
{
if (head == null) return null;
//begining point of the sorted list, set a sentinel
ListNode rtn = new ListNode(0);
ListNode cur = head; //node is inserting
ListNode pre = rtn; //insert node between pre and pre.next
while (cur != null)
{
ListNode next = cur.next;//save the node that will be inserted.
//until finding the position meets iter.val <= pre.next.val
while (pre.next != null && pre.next.val < cur.val)
{
pre = pre.next;
}
//insert between pre and pre.next
cur.next = pre.next;
pre.next = cur;
pre = rtn;
cur = next;
}
return rtn.next;
}
}