#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
typedef struct Node* List;
List init();
List add(List l, int x);
void print(List l);
List rep_delete(List l, int m, int n);
List clean(List l);
int main() {
List l;
int i;
l = init();
for (i=1; i<=8; i++)
l = add(l, i);
print(l);
l = rep_delete(l, 2, 2);
print(l);
l = clean(l);
return 0;
}
List init() {
return (List) NULL;
}
List add(List l, int x) {
List res;
if (!l) {
res = (struct Node *) malloc(sizeof(struct Node));
res->next = NULL;
res->data = x;
return res;
}
res = l;
while (l->next)
l = l->next;
l->next = (struct Node *) malloc(sizeof(struct Node));
l->next->next = NULL;
l->next->data = x;
return res;
}
void print(List l) {
if (!l)
return;
printf("%d", l->data);
l = l->next;
while (l) {
printf("->%d", l->data);
l = l->next;
}
printf("\n");
}
List rep_delete(List l, int m, int n) {
int i = 1;
int keep = 1;
List res = l;
struct Node* tmp;
if (!l) {
return l;
}
while (l->next) {
i++;
if (keep) {
if ( i == m) {
keep = 0;
i = 0;
}
l = l->next;
}
else {
tmp = l->next;
l->next = tmp->next;
free(tmp);
if (i == n) {
keep = 1;
i = 0;
}
}
}
return res;
}
List clean(List l) {
struct Node* tmp;
while (l) {
tmp = l->next;
free(l);
l = tmp;
}
return NULL;
}
Comments
Leave a comment