Skip to content

Commit d2902a6

Browse files
committed
Added to Linked-List
1 parent f16d766 commit d2902a6

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
2+
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
3+
You may not alter the values in the list's nodes, only nodes themselves may be changed.
4+
5+
Example :
6+
7+
1 ---> 2 ---> 3 ---> 4 ---> 5
8+
9+
becomes
10+
11+
2 ---> 1 ---> 4 ---> 3 ---> 5
12+
13+
14+
Input: head = [1,2,3,4,5], k = 2
15+
Output: [2,1,4,3,5]
16+
17+
Follow-up: Can you solve the problem in O(1) extra memory space?
18+
*/
19+
20+
#include <bits/stdc++.h>
21+
using namespace std;
22+
23+
struct ListNode
24+
{
25+
int val;
26+
ListNode *next;
27+
ListNode(int n)
28+
{
29+
val = n;
30+
next = NULL;
31+
}
32+
};
33+
34+
void printList(ListNode* head){
35+
int i = 0;
36+
while(head){
37+
cout<<head->val<<" ";
38+
head = head->next;
39+
}
40+
}
41+
42+
ListNode* reverseKGroup(ListNode* head, int k) {
43+
ListNode* curr = head;
44+
int count = 0;
45+
while (curr != NULL && count != k) {
46+
curr = curr->next;
47+
count++;
48+
}
49+
if (count == k) {
50+
curr = reverseKGroup(curr, k);
51+
while (count-- > 0) {
52+
ListNode* tmp = head->next;
53+
head->next = curr;
54+
curr = head;
55+
head = tmp;
56+
}
57+
head = curr;
58+
}
59+
return head;
60+
}
61+
62+
int main()
63+
{
64+
int NumOfNodes, nn, data, k;
65+
//cout<<"Enter no. ot nodes\n";
66+
cin>>NumOfNodes;
67+
nn = NumOfNodes;
68+
ListNode* head = NULL;
69+
ListNode* tail = head;
70+
71+
//cout<<"Enter data\n";
72+
while(nn--){
73+
cin>>data;
74+
if(!head){
75+
head = new ListNode(data);
76+
tail = head;
77+
}
78+
else{
79+
tail->next = new ListNode(data);
80+
tail = tail->next;
81+
}
82+
}
83+
//cout<<"\nK = ";
84+
cin>>k;
85+
ListNode* finalHead = reverseKGroup(head, k);
86+
printList(finalHead);
87+
return 0;
88+
}
89+
//No extra space used.
90+

0 commit comments

Comments
 (0)