Skip to content

Commit 6a6db1c

Browse files
↔️ Day 13
1 parent b32d49b commit 6a6db1c

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
3. [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3490/) ➡️ [CPP Solution](Week2/findMinArrowShots.cpp)
2222
4. [Remove Duplicate Letters](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3491/) ➡️ [CPP Solution](Week2/removeDuplicateLetters.cpp)
2323
5. [Buddy Strings](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3492/) ➡️ [CPP Solution](Week2/buddyStrings.cpp)
24+
6. [Sort List](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3493/) ➡️ [CPP Solution](Week2/sortList.cpp)
2425

2526
## Week 3 🚧
2627

Week2/sortList.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
private:
13+
ListNode* findMiddleNode(ListNode* head) {
14+
ListNode* slow = head;
15+
ListNode* fast = head->next;
16+
17+
while(fast != NULL && fast->next != NULL) {
18+
fast = fast->next->next;
19+
slow = slow->next;
20+
}
21+
ListNode* mid = slow->next;
22+
slow->next = NULL;
23+
24+
return mid;
25+
}
26+
27+
ListNode* mergeList(ListNode* l1, ListNode* l2) {
28+
ListNode* dummyHead = new ListNode(-1);
29+
ListNode* current = dummyHead;
30+
31+
while(l1 != NULL && l2 != NULL) {
32+
if(l1->val <= l2->val) {
33+
current->next = l1;
34+
l1 = l1->next;
35+
} else {
36+
current->next = l2;
37+
l2 = l2->next;
38+
}
39+
40+
current = current->next;
41+
}
42+
43+
current->next = l1 != NULL ? l1 : l2;
44+
45+
return dummyHead->next;
46+
}
47+
public:
48+
ListNode* sortList(ListNode* head) {
49+
if(head == NULL || head->next == NULL)
50+
return head;
51+
52+
ListNode* middle = findMiddleNode(head);
53+
54+
ListNode* left = sortList(head);
55+
ListNode* right = sortList(middle);
56+
57+
return mergeList(left, right);
58+
}
59+
};

0 commit comments

Comments
 (0)