Skip to content

Commit 9ad6ee2

Browse files
committed
Day-23 Linkedlist: reverse nodes and append
1 parent 041be8b commit 9ad6ee2

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* Given a linked list, reverse alternate nodes and append at the end
3+
* Examples:
4+
* Input List: 1->2->3->4->5->6
5+
* Output List: 1->3->5->6->4->2
6+
*
7+
* Input List: 12->14->16->18->20
8+
* Output List: 12->16->20->18->14
9+
*/
10+
11+
#include <iostream>
12+
13+
struct Node {
14+
int data;
15+
Node * next;
16+
Node(int d) : data{ d }, next{ nullptr } { }
17+
};
18+
19+
void insertAtHead( Node * & head, Node * node ) {
20+
if ( head != nullptr ) {
21+
node->next = head;
22+
}
23+
head = node;
24+
}
25+
26+
void insert( Node * & head, int data ) {
27+
Node * newNode = new Node(data);
28+
if ( head == nullptr ) {
29+
head = newNode;
30+
} else {
31+
Node * curr = head;
32+
while( curr->next ) {
33+
curr = curr->next;
34+
}
35+
curr->next = newNode;
36+
}
37+
}
38+
39+
void printList( Node * head ) {
40+
while( head ) {
41+
std::cout << head->data << "-->";
42+
head = head->next;
43+
}
44+
std::cout << "NULL" << std::endl;
45+
}
46+
47+
/* Algorithm function */
48+
void rearrange( Node * & head ) {
49+
if ( head == nullptr ) {
50+
return;
51+
}
52+
Node * curr = head;
53+
Node * forw = head->next;
54+
if ( forw == nullptr ) {
55+
return;
56+
}
57+
Node * backHead = nullptr;
58+
while ( curr != nullptr && forw != nullptr ) {
59+
curr->next = forw->next;
60+
forw->next = nullptr;
61+
insertAtHead( backHead, forw );
62+
curr = curr->next;
63+
if (curr != nullptr ) {
64+
forw = curr->next;
65+
}
66+
}
67+
//adding the backlist to mainlist again.
68+
curr = head;
69+
while ( curr->next != nullptr ) {
70+
curr = curr->next;
71+
}
72+
curr->next = backHead;
73+
}
74+
75+
int main() {
76+
Node * head = nullptr;
77+
insert( head, 1 );
78+
insert( head, 2 );
79+
insert( head, 3 );
80+
insert( head, 4 );
81+
insert( head, 5 );
82+
insert( head, 6 );
83+
std::cout << "List before rearrange: ";
84+
printList( head );
85+
rearrange( head );
86+
std::cout << "List after rearrange: ";
87+
printList( head );
88+
89+
Node * head2 = nullptr;
90+
insert( head2, 12 );
91+
insert( head2, 14 );
92+
insert( head2, 16 );
93+
insert( head2, 18 );
94+
insert( head2, 20 );
95+
std::cout << "List before rearrange: ";
96+
printList( head2 );
97+
rearrange( head2 );
98+
std::cout << "List after rearrange: ";
99+
printList( head2 );
100+
101+
return 0;
102+
}

0 commit comments

Comments
 (0)