-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp185.cpp
119 lines (105 loc) · 2.2 KB
/
p185.cpp
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* next;
};
void print(node*);
struct node* create_node(int x)
{
struct node* temp = new node;
temp -> data = x;
temp -> next = NULL;
return temp;
}
void push(node** head, int x)
{
struct node* store = create_node(x);
if (*head == NULL) {
*head = store;
return;
}
struct node* temp = *head;
while (temp -> next) {
temp = temp -> next;
}
temp -> next = store;
}
void split_list(node* head, node** a, node** b)
{
struct node* fast = head -> next;
struct node* slow = head;
while (fast != NULL && fast -> next != NULL) {
slow = slow -> next;
fast = fast -> next -> next;
}
struct node* temp = slow -> next;
slow -> next = NULL;
*a = head;
*b = temp;
}
struct node* reverse(node* b)
{
struct node* curr = b;
struct node* next = NULL;
struct node* prev = NULL;
while (curr != NULL) {
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
}
return prev;
}
void merge(node* a, node* b, node** c)
{
struct node* temp = a;
*c = create_node(0);
struct node* curr = *c;
while (temp && b) {
curr -> next = create_node(temp -> data - b -> data);
b = b -> next;
temp = temp -> next;
curr = curr -> next;
}
if (b != NULL) {
curr -> next = b;
curr = curr -> next;
}
curr -> next = reverse(a);
*c = (*c) -> next;
}
struct node* modifyTheList(struct node* head)
{
struct node* a;
struct node* b;
struct node* c;
split_list(head, &a, &b);
struct node* temp = reverse(b);
merge(temp, a, &c);
return c;
}
void print(node* head)
{
struct node* temp = head;
while (temp) {
cout << temp -> data << " ";
temp = temp -> next;
}
}
int main()
{
struct node* l = NULL;
push(&l, 1);
push(&l, 2);
push(&l, 3);
push(&l, 4);
push(&l, 5);
push(&l, 6);
cout << "Before the modify operation" << endl;
print(l);
l = modifyTheList(l);
cout << "\nAfter the modify operation" << endl;
print(l);
return 0;
}