147. Insertion Sort List
Description
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
Idea
Just use the Insertion Sort.
Or store the elements in vector and sort it first. But this is not inplace sort.
Solution
/**
* 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 prehead(0);
prehead.next = head;
ListNode *p1 = head->next;
ListNode *preP1 = head;
ListNode *postP1 = p1->next;
while (p1) {
ListNode *tmp = prehead.next;
ListNode *pre = &prehead;
while (tmp != p1) {
if (tmp->val < p1->val) {
pre = tmp;
tmp = tmp->next;
} else {
// found the right place to insert p1
p1->next = tmp;
pre->next = p1;
preP1->next = postP1;
p1 = postP1;
if (p1)
postP1 = p1->next;
break;
}
}
if (tmp == p1) {
preP1 = p1;
p1 = p1->next;
if (p1)
postP1 = p1->next;
}
}
return prehead.next;
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
values = []
while head:
values.append(head.val)
head = head.next
values.sort()
res = ListNode(values[0])
p = res
for i in range(1, len(values)):
tmp = ListNode(values[i])
p.next = tmp;
p = p.next
return res