-
Notifications
You must be signed in to change notification settings - Fork 368
/
Reverse in group of K.c
84 lines (74 loc) · 1.75 KB
/
Reverse in group of 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
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int x) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = NULL;
return newNode;
}
struct Node* insert(struct Node* head, int val) {
struct Node* temp = createNode(val);
if (head == NULL) {
temp->next = head;
return temp;
}
struct Node* curr = head;
while (curr->next != NULL)
curr = curr->next;
curr->next = temp;
temp->next = NULL;
return head;
}
struct Node* reverseinK(struct Node* head, int k) {
struct Node* curr = head;
struct Node* prevFirst = NULL;
int isFirstPass = 1;
while (curr != NULL) {
struct Node* first = curr;
struct Node* prev = NULL;
int count = 0;
while (curr != NULL && count < k) {
struct Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
count++;
}
if (isFirstPass) {
head = prev;
isFirstPass = 0;
}
else
prevFirst->next = prev;
prevFirst = first;
}
return head;
}
void print(struct Node* head) {
struct Node* curr = head;
printf("\n\n");
while (curr != NULL) {
printf("%d->", curr->data);
curr = curr->next;
}
printf("NULL\n\n");
}
int main() {
struct Node* head = NULL;
int n, val, k;
printf("Enter n, k : ");
scanf("%d %d", &n, &k);
printf("Enter nodes : \n");
for (int i = 0; i < n; i++) {
scanf("%d", &val);
head = insert(head, val);
}
print(head);
head = reverseinK(head, k);
print(head);
return 0;
}