-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.cpp
More file actions
83 lines (75 loc) · 1.66 KB
/
InsertionSortList.cpp
File metadata and controls
83 lines (75 loc) · 1.66 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*Question:
Insertion Sort List
Asked in:
Microsoft
Google
Sort a linked list using insertion sort.
We have explained Insertion Sort at Slide 7 of Arrays
Insertion Sort Wiki has some details on Insertion Sort as well.*/
//vector:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode *Solution::insertionSortList(ListNode *A)
{
vector<int> v;
struct ListNode *cur = A;
while (cur)
{
v.push_back(cur->val);
cur = cur->next;
}
cur = A;
int i = 0;
sort(v.begin(), v.end());
while (cur)
{
cur->val = v[i];
i++;
cur = cur->next;
}
return A;
}
//Linked List:
ListNode *insertionSortList(ListNode *head)
{
if (!head)
return head;
if (!head->next)
return head;
ListNode *sorted = NULL;
ListNode *list = head;
while (list)
{
ListNode *curr = list;
list = list->next;
if (sorted == NULL || sorted->val > curr->val)
{
// first lookup
curr->next = sorted; //this indicates the end of sorted list
sorted = curr;
}
else
{
// insert somewhere after the fisrt of sorted
ListNode *tmp = sorted;
while (tmp)
{
ListNode *s = tmp;
tmp = tmp->next;
if (s->next == NULL || s->next->val > curr->val)
{
s->next = curr;
curr->next = tmp;
break;
}
}
}
}
return sorted;
}