-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSortList.h
57 lines (49 loc) · 1.55 KB
/
InsertionSortList.h
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Author: naiyong, aonaiyong@gmail.com
Date: Sep 21, 2014
Problem: Insertion Sort List
Difficulty: 2
Source: https://oj.leetcode.com/problems/insertion-sort-list/
Notes:
Sort a linked list using insertion sort.
Solution: Insertion Sort.
http://en.wikipedia.org/wiki/Insertion_sort
http://www.sorting-algorithms.com/insertion-sort
*/
#ifndef INSERTIONSORTLIST_H_
#define INSERTIONSORTLIST_H_
#include "ListNode.h"
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (!head) return nullptr;
ListNode dummy(0), *tail = head;
dummy.next = head;
while (tail->next) {
ListNode *curr = tail->next;
if (tail->val <= curr->val)
tail = tail->next;
else {
ListNode *node = &dummy;
while (node->next->val <= curr->val)
node = node->next;
tail->next = curr->next;
curr->next = node->next;
node->next = curr;
}
// ListNode *curr = tail->next;
// ListNode *node = &dummy;
// while (node != tail && node->next->val <= curr->val)
// node = node->next;
// if (node == tail)
// tail = tail->next;
// else {
// tail->next = curr->next;
// curr->next = node->next;
// node->next = curr;
// }
}
return dummy.next;
}
};
#endif /* INSERTIONSORTLIST_H_ */