单链表的增删改查实例:
#include <stdio.h> #include <stdlib.h> typedef struct LinkedList { int elem; LinkedList * next; }List,* PList; PList CreateLinkedList(int size); void DisplayLinkedList(PList L); void InsertLinkedList(PList L,int locate,int elem); void DeleteLinkedList(PList L,int locate); void main() { int size; PList L; printf("输入此单链表的大小:"); scanf("%d",&size); L = CreateLinkedList(size); // 新建和显示 DisplayLinkedList(L); printf("\n在位置5插入元素2后\n"); InsertLinkedList(L,5,2); // 插入并显示 DisplayLinkedList(L); printf("\n删除位置3元素后\n"); DeleteLinkedList(L,3); // 删除3并显示 DisplayLinkedList(L); } PList CreateLinkedList(int size) { PList P,L; L = (PList)malloc(sizeof(List)); L->elem = 0; L->next = NULL; P = L; for (int i = 0; i < size; i++) { P->next = (PList)malloc(sizeof(List)); // 首先分配空间 然后再赋值 P = P->next; P->elem = rand()%100; P->next = NULL; } return L; } void DisplayLinkedList(PList L) { PList P = L; while (P->next != NULL) { P = P->next; printf("%d\t",P->elem); } printf("\n"); } void InsertLinkedList(PList L,int elem) // 在 Locate位置上面插入元素 elem { PList P = L; PList Q = NULL; if (locate != 0) locate--; while (P->next != NULL && locate != 0) { locate--; P = P->next; } if (locate != 0) printf("\n输入的范围有误\n"); else { Q = (PList)malloc(sizeof(List)); // 包含了 在最后插入 Q->elem = elem; Q->next = P->next; P->next = Q; } } void DeleteLinkedList(PList L,int locate) { PList P = L; PList Q = NULL; if (locate != 0) locate--; while (P->next != NULL && locate != 0) { locate--; P = P->next; } if (locate != 0) printf("\n输入的范围有误\n"); else { Q = P->next; P->next = P->next ->next; free(Q); } }原文链接:https://www.f2er.com/datastructure/383115.html