Skip to content

Commit 2010643

Browse files
🐎 Day 20
1 parent a7c9084 commit 2010643

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
3. [Distribute Candies to People](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/550/week-2-august-8th-august-14th/3427/) ➡️ [CPP Solution](Week3/distributeCandies.cpp)
2929
4. [Numbers With Same Consecutive Differences](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/550/week-2-august-8th-august-14th/3428/) ➡️ [CPP Solution](Week3/numsSameConsecDiff.cpp)
3030
5. [Goat Latin](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/550/week-2-august-8th-august-14th/3429/) ➡️ [CPP Solution](Week3/toGoatLatin.cpp) [JS Solution](Week3/toGoatLatin.js)
31+
6. [Reorder List](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/550/week-2-august-8th-august-14th/3430/) ➡️ [CPP Solution](Week3/reorderList.cpp)
3132

3233
## Week 4 🚧
3334
Coming Soon...

Week3/reorderList.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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+
void reverseList(ListNode** head) {
13+
ListNode* next;
14+
ListNode* prev = NULL;
15+
ListNode* curr = *head;
16+
17+
while (curr) {
18+
next = curr->next;
19+
curr->next = prev;
20+
prev = curr;
21+
curr = next;
22+
}
23+
24+
*head = prev;
25+
}
26+
public:
27+
void reorderList(ListNode* head) {
28+
if(head == NULL) return;
29+
30+
ListNode* fast = head->next;
31+
ListNode* slow = head;
32+
33+
while(fast && fast->next) {
34+
fast = fast->next->next;
35+
slow = slow->next;
36+
}
37+
38+
ListNode* head1 = head;
39+
ListNode* head2 = slow->next;
40+
41+
slow->next = NULL;
42+
43+
reverseList(&head2);
44+
45+
head = new ListNode(0);
46+
47+
ListNode* curr = head;
48+
49+
while(head1 || head2) {
50+
51+
if(head1) {
52+
curr->next = head1;
53+
curr = curr->next;
54+
head1 = head1->next;
55+
}
56+
57+
if(head2) {
58+
curr->next = head2;
59+
curr = curr->next;
60+
head2 = head2->next;
61+
}
62+
63+
}
64+
65+
head = head->next;
66+
}
67+
};

0 commit comments

Comments
 (0)