/
mnlist.c
134 lines (100 loc) · 2.24 KB
/
mnlist.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
125
126
127
128
129
130
131
132
133
134
//Program to alter a linked list with given two integers M & N .keep M nodes and delete N nodes repetitively.
#include<stdio.h>
#include<stdlib.h>
//Declare a linked list
struct node{
int data;
struct node *next;
};
struct node *head;
int flag=1;
//Create a node of a linked list
struct tree *create_node(int data){
struct node *temp=(struct node*)malloc(sizeof(struct node));
if(!temp)
{ printf("Memory error");
return;
}
temp->data=data;
temp->next=NULL;
return temp;
}
//Delete n nodes from given node(including node)
struct node *delete_node_from(struct node *left,int n){
//counter for counting nodes to be deleted
int counter=0;
struct node *temp;
struct node *nxt;
temp=left;
if(!n || !left)
return left;
while(temp!=NULL && counter!=n){
nxt=temp->next;
printf("Node- %d being deleted\n",temp->data);
free(temp);
temp=NULL;
counter++;
//if counter equals 'n' return else proceed
temp=nxt;
if(counter==n)
return temp;
}
//set flag here
flag=0;
return temp;
}
//Keep 'M' node of a linked list
struct node *keep_node(struct node *left,int m){
//Counter
int counter=0;
struct node *temp=left;
if(!m || !left)
return left;
while(temp!=NULL && counter!=m){
counter++;
if(counter==m)
return temp;
else
temp=temp->next;
}
//set flag here
flag=0;
return temp;
}
void alter_list(int m,int n){
struct node *temp=head;
if(m==0){
printf("M can't be zero\n");
return;
}
while(flag==1 && temp!=NULL){
if(flag==1)
temp=keep_node(temp,m);
if(flag==1) {
temp->next=delete_node_from(temp->next,n);
temp=temp->next; }
}
}
//Display a linked list
void display_list(){
struct node *temp=head;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void main(){
int m=2,n=3;
struct node *t1=create_node(2);
head=t1;
t1->next=create_node(5);
t1->next->next=create_node(7);
t1->next->next->next=create_node(9);
t1->next->next->next->next=create_node(11);
t1->next->next->next->next->next=create_node(13);
t1->next->next->next->next->next->next=create_node(15);
display_list();
alter_list(m,n);
display_list();
}