题目网址:https://www.dotcpp.com/oj/problem1676.html
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
typedef struct node NODE;
NODE *creat(int n) {
NODE *h, *p, *q;
int i, flag = 0;
h = (NODE *)malloc(sizeof(NODE));
p = h;
for (i = 0; i < n; i++) {
q = (NODE *)malloc(sizeof(NODE));
scanf("%d", &q->data);
if (flag == 0) {
p->next = q;
p = q;
p->next = NULL;
flag = 1;
} else {
h->next = q;
q->next = p;
p = q;
}
}
return h;
}
void get_(NODE *h, int x) {
NODE *p;
int i;
p = h;
for (i = 0; i < x; i++) {
p = p->next;
if (p == NULL)
break;
}
if (p != NULL)
printf("%d\n", p->data);
else
printf("get fail\n");
}
void insert_(NODE *h, int x, int y) {
NODE *p, *q;
int i = 0;
p = h;
while (p != NULL && i < x - 1) {
p = p->next;
i++;
}
if (i < x - 1)
printf("insert fail\n");
else {
q = (NODE *)malloc(sizeof(NODE));
q->data = y;
q->next = p->next;
p->next = q;
printf("insert OK\n");
}
}
void delete_(NODE *h, int x) {
NODE *p, *q;
int i = 0;
p = h;
while (p->next != NULL && i < x - 1) {
p = p->next;
i++;
}
if (p->next == NULL)
printf("delete fail\n");
else {
printf("delete OK\n");
q = p->next;
p->next = q->next;
free(q);
}
}
void show_(NODE *h) {
NODE *p;
p = h;
if (p->next == NULL)
printf("Link list is empty\n");
else {
p = p->next;
do {
printf("%d ", p->data);
p = p->next;
} while (p != NULL);
printf("\n");
}
}
int main() {
int n, m, x, y;
char a[10] = {0};
scanf("%d", &n);
NODE *h;
h = creat(n);
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%s", a);
if (a[0] == 'g') {
scanf("%d", &x);
get_(h, x);
} else if (a[0] == 'i') {
scanf("%d%d", &x, &y);
insert_(h, x, y);
} else if (a[0] == 'd') {
scanf("%d", &x);
delete_(h, x);
} else if (a[0] == 's')
show_(h);
}
return 0;
}