diff --git a/C++/143.Reorder_List.cpp b/C++/143.Reorder_List.cpp new file mode 100644 index 00000000..b88c9c21 --- /dev/null +++ b/C++/143.Reorder_List.cpp @@ -0,0 +1,45 @@ +/* medium difficulty */ + +class Solution { +public: + void reorderList(ListNode* head) { + + //edge cases + if ((!head) || (!head->next) || (!head->next->next)) return; + + int l=0; //to calculate the length + ListNode* curr=head; + while(curr){ + l++; + curr=curr->next; + } + + //stack to store the second half of the elements of the ll + stack s; + curr=head; + + //iterating till the end of the first half + int m=(l+1)/2; + while(m>=1){ + curr=curr->next; + m--; + } + + //pushing the second half of the elements in the stack + while(curr){ + s.push(curr); + curr=curr->next; + } + + //attaching the elements from the top of the stack to the first half of the elements + curr=head; + while(curr&&!s.empty()){ + ListNode* temp=s.top(); + s.pop(); + temp->next=curr->next; + curr->next=temp; + curr=curr->next->next; + } + curr->next=NULL; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index b13f42ee..c93108c0 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,9 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) | [Java](./Java/linked-list-cycle-ii.java)
[C++](./C++/Linked-List-Cycle-II.cpp) | _O(n)_ | _O(1)_ | Medium | Slow-Fast Pointers | | | 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/LRU-Cache.cpp)
[Python](./Python/LRUCache.py) | _O(1)_ | _O(k)_ | Medium | Hash Map | | | 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | [Java](./Java/intersection-of-two-linked-lists.java) | _O(n)_ | _O(1)_ | Easy | Two Pointers | [Tutorial](https://youtu.be/uozGB0-gbvI) | -| 186 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Java](./Java/middle-of-the-linked-list.java) | _O(n)_ | _O(1)_ | Easy | Two pointers | | +| 186 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Java](./Java/middle-of-the-linked-list.java) | _O(n)_ | _O(1)_ | Easy | Two pointers | +| 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | [C++](./C++/143.Reorder_List.cpp) | _O(n)_ | _O(n)_ | Medium | Iteration and Stack | + |