147. Insertion Sort List
Sort a linked list using insertion sort.
解法:
Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.
First, a quick recap of insertion sort:
Start from the second element (simply a[1] in array and the annoying head -> next -> val in linked list), each time when we see a node with val smaller than its previous node, we scan from the head and find the position that the current node should be inserted. Since a node may be inserted before head, we create a new_head that points to head. The insertion operation, however, is a little easier for linked list.
Now comes the code:
/**
* 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||!head->next) return head;
ListNode* new_head ;
new_head->next = head;
ListNode* pre = new_head;
ListNode* cur = head;
while(cur) {
if(cur->next && cur->next->val < cur->val) {
while(pre->next && pre->next->val < cur->next->val) pre = pre->next;
ListNode* temp = pre->next;
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = temp;
pre = new_head;
}
else cur = cur->next;
}
return new_head->next;
}
};
方法二:
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head) {
ListNode *dummy = new ListNode(0);
// 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里
// 所以这里不需要dummy->next = head;
while (head != NULL) {
ListNode *temp = dummy;
ListNode *next = head->next;
while (temp->next != NULL && temp->next->val < head->val) {
temp = temp->next;
}
head->next = temp->next;
temp->next = head;
head = next;
}
return dummy->next;
}
};