C语言链表解题
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned long long ull; typedef long long ll; #define MAXV 1007 typedef struct node { int data; struct node *next; } *List, Node; void PrintList(List L) { List p = L->next; if (p == NULL) { printf("NULL"); return; } while (p != NULL) { printf("%d ", p->data); p = p->next; } } // 获取目标数的下标 List GetIdx(List L, int x) { List p = L->next; while (p != NULL) if (p->data == x) break; else p = p->next; return p; } void InsertList(List *L, int y, List idx) { List s, t; t = (*L); while (t->next != idx) t = t->next; s = (List) malloc(sizeof(Node)); s->data = y; s->next = t->next; t->next = s; } void DeleteList(List *L, List idx) { if (idx == NULL) return; List t = (*L); while (t->next != idx) t = t->next; t->next = idx->next; free(idx); } int main() { List L = (List) malloc(sizeof(Node)); L->next = NULL; int n; scanf("%d", &n); for (int i = 0; i < n; ++i) { char ope[20]; int x, y; scanf("%s", ope); strcmp("insert", ope) == 0 ? scanf("%d %d", &x, &y) : scanf("%d", &x); if (strcmp("insert", ope) == 0) InsertList(&L, y, GetIdx(L, x)); else if (strcmp("delete", ope) == 0) DeleteList(&L, GetIdx(L, x)); } PrintList(L); return 0; }