-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderList.cpp
More file actions
102 lines (82 loc) · 1.55 KB
/
Copy pathReorderList.cpp
File metadata and controls
102 lines (82 loc) · 1.55 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<bits/stdc++.h>
using namespace std;
class LinkedList {
public:
int data;
LinkedList* next;
LinkedList(int _data) {
data = _data;
next = NULL;
}
};
LinkedList* createList(LinkedList* head, int data) {
if(head == NULL)
return new LinkedList(data);
LinkedList* temp = head;
while(head->next) {
head = head->next;
}
head->next = new LinkedList(data);
return temp;
}
void display(LinkedList* head) {
if(head == NULL)
return;
while(head->next) {
cout << head->data << "->";
head = head->next;
}
cout << head->data << endl;
}
LinkedList* reverseList(LinkedList* head) {
if(head == NULL)
return head;
LinkedList* prev = NULL;
LinkedList* curr = head;
LinkedList* temp = head;
while(temp) {
temp = temp->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
LinkedList* reorderList(LinkedList* head) {
if(head == NULL)
return head;
LinkedList* slow = head;
LinkedList* fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
slow->next = reverseList(slow->next);
//display(head);
// 3->4->5->6
// p2 p1 t
LinkedList* p1 = slow;
LinkedList* temp = NULL;
LinkedList* p2 = head;
while(p1->next && p2->next && p1 != p2) {
temp = p1->next;
p1->next = temp->next;
temp->next = p2->next;
p2->next = temp;
p2 = p2->next->next;
}
return head;
}
int main() {
int data;
cin >> data;
LinkedList* head = NULL;
while(data != -1) {
head = createList(head, data);
cin >> data;
}
display(head);
head = reorderList(head);
display(head);
return 0;
}