-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.cpp
More file actions
35 lines (27 loc) · 906 Bytes
/
InsertionSortList.cpp
File metadata and controls
35 lines (27 loc) · 906 Bytes
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
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode dummy_node(0);
ListNode *travel_node = head;
while (travel_node) {
ListNode *insert_pos = &dummy_node;
while (insert_pos->next && insert_pos->next->val < travel_node->val)
insert_pos = insert_pos->next;
ListNode *next_node = travel_node->next;
travel_node->next = insert_pos->next;
insert_pos->next = travel_node;
travel_node = next_node;
}
return dummy_node.next;
}
};