forked from anshuman8800/Interivew-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReversingKNodesLL.cpp
More file actions
90 lines (90 loc) · 1.33 KB
/
ReversingKNodesLL.cpp
File metadata and controls
90 lines (90 loc) · 1.33 KB
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
#include <bits/stdc++.h>
using namespace std;
// linked list
class node
{
public:
int data;
node *next;
node(int k)
{
data = k;
next = NULL;
}
};
void IAT(node *&head, int p) // Inserting element at the tail
{
node *n = new node(p);
if (head == NULL)
{
head = n;
return;
}
node *t = head;
while (t->next != NULL)
{
t = t->next;
}
t->next = n;
}
void print(node *&head) // for printing the linked list
{
node *t = head;
while (t != NULL)
{
cout << t->data << " -> ";
t = t->next;
}
cout<<"NULL\n";
}
int leng(node *&head) // for finding the length of the linked list
{
node *t = head;
int l = 0;
while (t != NULL)
{
l++;
t = t->next;
}
return l;
}
node *revk(node *&head, int k) // for reversing k nodes
{
if(k>leng(head)){
cout<<"k is greater than length of the linked list\n";
return head;
}
node *pre = NULL;
node *cur = head;
node *ne;
int c = 0;
while (cur != NULL && c < k)
{
ne = cur->next;
cur->next = pre;
pre = cur;
cur = ne;
c++;
}
if (ne != NULL)
{
head->next = revk(ne, k);
}
return pre;
}
int main()
{
node *head = NULL;
IAT(head, 1);
IAT(head, 2);
IAT(head, 3);
IAT(head, 4);
IAT(head, 5);
IAT(head, 6);
cout<<"Linked List before reversing k nodes\n";
print(head);
node *temp = revk(head, 2);
cout<<"Linked List after reversing k nodes\n";
print(temp);
return 0;
}