forked from vivekanand44/codes-Youtube-videos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse linked list in a group of size k.c
124 lines (99 loc) · 1.77 KB
/
reverse linked list in a group of size k.c
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
void reverse(node *head)
{
if(head == NULL)
return;
if(head -> next == NULL)
return;
reverse(head->next);
head->next->next = head;
head->next = NULL;
}
node *swap_in_a_group(node *start , int k)
{
//swap the linked list in group size = k
node *p , *q ,*new_start , *temp;
int cnt;
p = start;
cnt = 0;
while(cnt != k-1) // go to the 'K'th node
{
if(p->next == NULL)
{
return start;
}
p = p->next;
cnt++;
}
new_start = p; //the new start
q = new_start;
while(1)
{
p = start;
temp = q->next;
if(temp == NULL) // if total number of nodes is divisible by K (multiple of K)
{
reverse(p);
return new_start;
}
q->next = NULL;
q = temp;
start = temp;
cnt = 0;
//in the last outside while loop , if remainder is non-zero number of nodes
while(cnt != k-1)
{
if(temp->next == NULL)
{
reverse(p);
p->next = q;
return new_start;
}
temp = temp->next;
cnt++;
}
reverse(p);
p->next = temp;
q = temp;
}
return new_start;
}
int main()
{
int a , i , n , cnt , k=4 , flag = 1;
node *p,*q,*start;
printf("Enter the number of nodes");
scanf("%d",&n);
printf("Enter all the nodes separated by space \n");
p = (node*)malloc(sizeof(node));
scanf("%d",&a);
p->data = a;
p->next = NULL;
start = p;
for(i=1;i<n;i++)
{
q = (node*)malloc(sizeof(node));
scanf("%d",&a);
q->data = a;
q->next = NULL;
p->next = q;
p = p->next;
}
printf("\n Enter K ");
scanf("%d",&k);
printf("\n swapped list==");
p = swap_in_a_group(start , k); //call the function
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
return 0;
}