MCPcopy Create free account
hub / github.com/Vishruth-S/CompetitiveCode / Solution

Class Solution

LeetCode_problems/Reorder_List/solution.cpp:61–100  ·  view source on GitHub ↗

* Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */

Source from the content-addressed store, hash-verified

59 * };
60 */
61class Solution {
62public:
63 void reorderList(ListNode* head) {
64 if(!head) return ;
65 ListNode* slow=head;
66 ListNode* fast=head->next;
67 while(fast && fast->next){
68 slow=slow->next;
69 fast=fast->next->next;
70 }
71 ListNode* newhead=slow->next;
72 slow->next=NULL;
73 newhead= reverse(newhead);
74 head= merge(head,newhead);
75
76 }
77 ListNode* merge(ListNode* l1,ListNode* l2){
78 if(!l1) return l2;
79 if(!l2) return l1;
80 ListNode* nexthead=l1->next;
81 l1->next=l2;
82 l2->next=merge(nexthead,l2->next);
83 return l1;
84 }
85
86 ListNode* reverse(ListNode* head){
87 ListNode* pre=NULL;
88 if(!head || !head->next)
89 return head;
90 ListNode* cur=head;
91 ListNode* next=NULL;
92 while(cur){
93 next=cur->next;
94 cur->next=pre;
95 pre=cur;
96 cur=next;
97 }
98 return pre;
99 }
100};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected