Leetcode Study Day 51 and 52

Sort List

Given the head of a linked list, return the list after sorting it in ascending order.

Example 1:
image

1
2
Input: head = [4,2,1,3]
Output: [1,2,3,4]

Example 2:
image

1
2
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
1
2
3
4
5
6
7
8
Example 3:

Input: head = []
Output: []

Constraints:
The number of nodes in the list is in the range [0, 5 * 104].
-105 <= Node.val <= 105

My solution

My solution actually doesn’t apply the divide and conquer method. I push each value in the node into a list and then sort it first. Then I create a new linked list and push the sorted list into the linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head == nullptr)
return head;
vector <int> storeValue;
ListNode * current = head;
while(current != nullptr){
storeValue.push_back(current->val);
current = current->next;
}
sort(storeValue.begin(), storeValue.end());
ListNode * newHead = new ListNode(storeValue[0]);
ListNode * newCurrent = newHead;
for (int i = 1; i < storeValue.size(); i++){
ListNode * nextNode = new ListNode(storeValue[i]);
newCurrent -> next= nextNode;
newCurrent = newCurrent -> next;
}
return newHead;
}
};

Divide and Conquer

I found one good explanation from the LeetCode.

The idea is:

1
2
3
1. Using 2pointer / fast-slow pointer find the middle node of the list.
2. Now call mergeSort for 2 halves.
3. Merge the Sort List (divide and conqueror Approach)

The code is :

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

class Solution {
public:
ListNode* sortList(ListNode* head) {
//If List Contain a Single or 0 Node
if(head == NULL || head ->next == NULL)
return head;


ListNode *temp = NULL;
ListNode *slow = head;
ListNode *fast = head;

// 2 pointer appraoach / turtle-hare Algorithm (Finding the middle element)
while(fast != NULL && fast -> next != NULL)
{
temp = slow;
slow = slow->next; //slow increment by 1
fast = fast ->next ->next; //fast incremented by 2

}
temp -> next = NULL; //end of first left half

ListNode* l1 = sortList(head); //left half recursive call
ListNode* l2 = sortList(slow); //right half recursive call

return mergelist(l1, l2); //mergelist Function call

}

//MergeSort Function O(n*logn)
ListNode* mergelist(ListNode *l1, ListNode *l2)
{
ListNode *ptr = new ListNode(0);
ListNode *curr = ptr;

while(l1 != NULL && l2 != NULL)
{
if(l1->val <= l2->val)
{
curr -> next = l1;
l1 = l1 -> next;
}
else
{
curr -> next = l2;
l2 = l2 -> next;
}

curr = curr ->next;

}

//for unqual length linked list

if(l1 != NULL)
{
curr -> next = l1;
l1 = l1->next;
}

if(l2 != NULL)
{
curr -> next = l2;
l2 = l2 ->next;
}

return ptr->next;
}
};
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信