Sort a linked list using insertion sort.
添加dummy头结点,作为结果链表的头。然后将输入链表的首元素加入返回链表,并将其与输入链表断开。
之后,对于输入链表中的每一个结点,在返回链表中找到合适的插入点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(!head)
return NULL;
ListNode *dummy = new ListNode(INT_MAX);
dummy->next = head;
ListNode *cur = head->next;
head->next = NULL;
while(cur)
{
ListNode *curNext = cur->next;
ListNode *tmpCur = dummy;
while(tmpCur->next && cur->val > tmpCur->next->val)
{
tmpCur = tmpCur->next;
}
cur->next = tmpCur->next;
tmpCur->next = cur;
cur = curNext;
}
return dummy->next;
}
};
一开始的第路是对的,但是。。问题就在没把两个链表断开。。。
LeetCode(147)Insertion Sort List这篇文章不错
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == 0 || head -> next == 0)
return head;
ListNode * cur = head;
ListNode * next = head;
ListNode * newHead = 0;
ListNode * newTail = 0;
while(cur)
{
next = cur -> next;
if(newHead == 0)
{
newHead = cur;
newTail = cur;
newTail -> next = 0;
}
else
{
ListNode * tmpPre = 0;
ListNode * tmpCur = newHead;
while(tmpCur && cur -> val > tmpCur -> val)
{
tmpPre = tmpCur;
tmpCur = tmpCur -> next;
}
if(tmpPre == 0)
{
cur->next = newHead;
newHead = cur;
}
else if(tmpCur == 0)
{
newTail -> next = cur;
newTail = cur;
newTail -> next = 0;
}
else
{
cur -> next = tmpCur;
tmpPre -> next = cur;
}
}
cur = next;
}
return newHead;
}
};