样例 Given 1->3->2->0->null, return 0->1->2->3->null
注意单链表插入排序和数组插入排序的不同:数组插入排序是从排好序的部分的最后一个节点往前找,找到第一个比它小的数,然后插到其后面;而单链表只能从前往后遍历,找到第一个比当前节点大的值结束,因此在遍历已经排好序的链表部分的时候,需要两个指针,一个指针用于往前遍历(该指针假设为遍历指针),一个指针用于记录遍历指针指向的当前节点的前一个节点(该指针假设为遍历指针),这样当遍历指针找到第一个比待插入节点的值大的节点的时候,就可以将待插入节点插入到记录指针的后面。(之所以使用两个指针,是因为单链表不能反指)
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The head of linked list. */ ListNode *insertionSortList(ListNode *head) { if(head==NULL||head->next==NULL) { return head; } ListNode*helper=new ListNode(0); ListNode*cur=head; ListNode*pre; while(cur!=NULL) { pre=helper; ListNode *next=cur->next; while(pre->next!=NULL&&pre->next->valval) { pre=pre->next; } cur->next=pre->next; pre->next=cur; cur=next; } return helper->next; // write your code here } };
