-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_ReverseAlternateNodesInLL.cpp
140 lines (120 loc) · 2.61 KB
/
GFG_ReverseAlternateNodesInLL.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
https://practice.geeksforgeeks.org/problems/given-a-linked-list-reverse-alternate-nodes-and-append-at-the-end/1#
Reverse alternate nodes in Link List
*/
// { Driver Code Starts
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
/* A linked list node */
struct Node
{
int data;
struct Node *next;
Node(int x){
data = x;
next = NULL;
}
};
struct Node *start = NULL;
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
void insert()
{
int n,value;
cin>>n;
struct Node *temp;
for(int i=0;i<n;i++)
{
cin>>value;
if(i==0)
{
start = new Node(value);
temp = start;
continue;
}
else
{
temp->next = new Node(value);
temp = temp->next;
}
}
}
// } Driver Code Ends
/*
reverse alternate nodes and append at the end
The input list will have at least one element
Node is defined as
struct Node
{
int data;
struct Node *next;
Node(int x){
data = x;
next = NULL;
}
};
*/
class Solution
{
public:
void rearrange(struct Node *head)
{
int n=2;
struct Node* cur = head->next;
struct Node* oddHead = head;
struct Node* odd = oddHead, *even = nullptr;
struct Node* cnxt;
//start frpm second node n=2
while(cur)
{
if(n&1) //if odd node, make its list
{
odd->next = cur;
odd = cur;
cur = cur->next;
}
else //if even node
{
cnxt = cur->next; // as we are going to change cur->next value in order to insert in beginign
if(!even) // if even node initialize first time
{
even = cur;
even->next = nullptr;
}
else
{
cur->next = even; //insertion in the begining //reversing
even = cur;
}
cur = cnxt; // next element in the list
}
n++;
}
odd->next = even;// merge both list
head = oddHead;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while (t--) {
insert();
Solution ob;
ob.rearrange(start);
printList(start);
}
return 0;
}
// } Driver Code Ends