Fork me on GitHub

Insertion Sort List

Description

https://leetcode.com/problems/insertion-sort-list/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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) {
ListNode* fakeHead = new ListNode(0);
fakeHead->next = NULL;
ListNode* cur = head;
while (cur != NULL) {
ListNode* pre = fakeHead;
int value = cur->val;
while(pre->next != NULL && value > pre->next->val)
pre = pre->next;
ListNode* temp = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = temp;
}
return fakeHead->next;
}
};