-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdraft1.cpp
More file actions
57 lines (56 loc) · 1.51 KB
/
draft1.cpp
File metadata and controls
57 lines (56 loc) · 1.51 KB
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
#include<iostream>
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) {}
};
class Solution {
public:
static ListNode* middleNode(ListNode* head) {
ListNode* l1=head;
ListNode* l2=head;
int cnt=0;
while(l2!=nullptr){
l2=l2->next;
if(cnt!=0&&cnt%2==0)l1=l1->next;
cnt++;
}
return l1;
}
static ListNode* reverseList(ListNode* head) {
ListNode* l1=nullptr;
ListNode* l2=head;
ListNode* l3;
if(head!=nullptr)l3=head->next;
while(l2!=nullptr){
l2->next=l1;
l1=l2;
l2=l3;
if(l3!=nullptr)l3=l3->next;
}
return l1;
}
static void reorderList(ListNode* head) {
ListNode* mid = middleNode(head);
ListNode* tar = head;
ListNode* reversedBack = reverseList(mid);
while(tar!=nullptr && reversedBack!=nullptr){
ListNode* headBf=tar->next;
ListNode* tailBf=reversedBack->next;
tar->next=reversedBack;
reversedBack->next=headBf;
tar=headBf;
reversedBack=tailBf;
}
}
};
int main(){
ListNode* a=new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5)))));
Solution::reorderList(a);
while(a!=nullptr){
std::cout<<a->val<<' ';
a=a->next;
}
}