-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverse-in-group.c
89 lines (88 loc) · 1.99 KB
/
reverse-in-group.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
//Problem
/*Given a singly linked list and an integer K, reverses the nodes of the
list K at a time and returns modified linked list.
NOTE : The length of the list is divisible by K
Example :
Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2,
You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5
Try to solve the problem using constant extra space.*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node listnode;
void insertAtEnd(struct node **s,int d)
{
struct node *new=(struct node *)malloc(sizeof(struct node));
struct node *curr=(struct node *)malloc(sizeof(struct node));
curr=*s;
while(curr->next!=NULL)
{
curr=curr->next;
}
new->data=d;
new->next=NULL;
curr->next=new;
}
listnode* reverseList(listnode* A, int k) {
listnode *previous=NULL;
listnode *curr=A;
listnode *next1=(struct node *)malloc(sizeof(struct node));
listnode *temp=curr;
listnode *temp1=(struct node *)malloc(sizeof(struct node));
int i=0,j=1;
while(curr!=NULL&&i<k)
{
next1=curr->next;
curr->next=previous;
previous=curr;
curr=next1;
i++;
if(i==k)
{
i=0;
if(j==1)
{
A=previous;
j=0;
}
else
{
temp->next=previous;
temp=temp1;
}
previous=NULL;
temp1=curr;
}
}
if(j==1)
A=previous;
if(j==0&&i!=0)
{
temp->next=previous;
}
return A;
}
int main()
{
struct node *s=(struct node *)malloc(sizeof(struct node));
insertAtEnd(&s,1);
insertAtEnd(&s,2);
insertAtEnd(&s,3);
insertAtEnd(&s,4);
insertAtEnd(&s,5);
insertAtEnd(&s,6);
insertAtEnd(&s,7);
insertAtEnd(&s,8);
insertAtEnd(&s,9);
insertAtEnd(&s,10);
s=reverseList(s,3); //3 mean group of three
while(s!=NULL)
{
printf("%d ",s->data);
s=s->next;
}
}