-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Reverse_LinkedList_Nodes_in_K-Groups.cpp
105 lines (98 loc) · 1.71 KB
/
Reverse_LinkedList_Nodes_in_K-Groups.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
/*
Given N, Linked List and K,
Reverse the Node of Linked List in Groups of K and return
example:
N=5
Linked list: 1 2 3 4 5
K=2
Answer 2 1 4 3 5
*/
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void push(Node **head, int data)
{
Node *new_node = new Node();
new_node->data = data;
(new_node)->next = (*head);
(*head) = new_node;
}
void printLL(Node *temp)
{
while (temp != NULL)
{
cout << temp->data << "->";
temp = temp->next;
}
}
Node *reverseK(Node *head, int k)
{
int flag = 0;
Node *temp = head;
while (temp)
{
temp = temp->next;
flag++;
if (flag == k)
break;
}
if (flag < k)
return head;
int count = 0;
Node *curr = head;
Node *prev = NULL, *next = NULL;
while (curr && count < k)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
count++;
}
if (next != NULL)
{
head->next = reverseK(next, k);
}
return prev;
}
int main()
{
Node *head = NULL;
int n;
cout << "Enter Numbers of Element N:";
cin >> n;
cout << "Enter elements:";
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
push(&head, a);
}
int k;
cout << "Enter K:";
cin >> k;
cout << "\nOriginal Linked List:\n";
printLL(head);
head = reverseK(head, k);
cout << "\nNew Linked List:\n";
printLL(head);
}
/*
Sample Input/Output:
Input:
Enter Numbers of Element N:5
Enter elements:1 2 3 4 5
Enter K:2
Output:
Original Linked List:
5->4->3->2->1->
New Linked List:
4->5->2->3->1->
Time-Complexity: O(n)
Space-Complexity: O(1)
*/