Skip to content

Commit 0294dec

Browse files
committed
Added the k-grouped reverse a linked list algorithm.
1 parent 7167c65 commit 0294dec

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// CPP program to reverse a linked list
2+
// in groups of given size
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
/* Link list node */
7+
class Node
8+
{
9+
public:
10+
int data;
11+
Node* next;
12+
};
13+
14+
/* Reverses the linked list in groups
15+
of size k and returns the pointer
16+
to the new head node. */
17+
Node *reverse (Node *head, int k)
18+
{
19+
Node* current = head;
20+
Node* next = NULL;
21+
Node* prev = NULL;
22+
int count = 0;
23+
24+
/*reverse first k nodes of the linked list */
25+
while (current != NULL && count < k)
26+
{
27+
next = current->next;
28+
current->next = prev;
29+
prev = current;
30+
current = next;
31+
count++;
32+
}
33+
34+
/* next is now a pointer to (k+1)th node
35+
Recursively call for the list starting from current.
36+
And make rest of the list as next of first node */
37+
if (next != NULL)
38+
head->next = reverse(next, k);
39+
40+
/* prev is new head of the input list */
41+
return prev;
42+
}
43+
44+
/* UTILITY FUNCTIONS */
45+
/* Function to push a node */
46+
void push(Node** head_ref, int new_data)
47+
{
48+
/* allocate node */
49+
Node* new_node = new Node();
50+
51+
/* put in the data */
52+
new_node->data = new_data;
53+
54+
/* link the old list off the new node */
55+
new_node->next = (*head_ref);
56+
57+
/* move the head to point to the new node */
58+
(*head_ref) = new_node;
59+
}
60+
61+
/* Function to print linked list */
62+
void printList(Node *node)
63+
{
64+
while (node != NULL)
65+
{
66+
cout<<node->data<<" ";
67+
node = node->next;
68+
}
69+
}
70+
71+
/* Driver code*/
72+
int main()
73+
{
74+
/* Start with the empty list */
75+
Node* head = NULL;
76+
77+
/* Created Linked list is 1->2->3->4->5->6->7->8->9 */
78+
push(&head, 9);
79+
push(&head, 8);
80+
push(&head, 7);
81+
push(&head, 6);
82+
push(&head, 5);
83+
push(&head, 4);
84+
push(&head, 3);
85+
push(&head, 2);
86+
push(&head, 1);
87+
88+
cout<<"Given linked list \n";
89+
printList(head);
90+
head = reverse(head, 3);
91+
92+
cout<<"\nReversed Linked list \n";
93+
printList(head);
94+
95+
return(0);
96+
}
97+
98+
// This code is contributed by Subrat Kumar Swain

0 commit comments

Comments
 (0)