单链表:
#include <stdio.h> #include <stdlib.h> //实现初始化,头插,尾插,删除,输出等单链表的基本操作 typedef struct Node { int data; struct Node* next; }Node; //初始化 Node* intList() { Node* list = (Node*)malloc(sizeof(Node)); list->data = 0; list->next = NULL; return list; } //头插法 void headInsert(Node* list, int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->next = list->next; list->next = node; list->data++; } //尾插法 void lastInsert(Node* list, int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->next = NULL; Node* head = list; while (list->next) { list = list->next; } list->next = node; head->data++; } //删除一个 void delect(Node* list,int data){ Node* cur = list->next; Node* pre = list; while (cur) { if (cur->data == data) { pre->next = cur->next; free(cur); list->data--; break; } pre = cur; cur = cur->next; } } //删除多个相同 void delectAll(Node* list, int data) { Node* cur = list->next; Node* pre = list; while (cur) { if (cur->data == data) { pre->next = cur->next; free(cur); cur = pre->next; list->data--; continue; } pre = cur; cur = cur->next; } } void printList(Node* list) { list = list->next; while (list) { printf("%d ",list->data); list = list->next; } printf("\n"); } int m() { Node* list = intList(); headInsert(list,1); headInsert(list,1); headInsert(list, 1); headInsert(list,2); headInsert(list,3); lastInsert(list, 4); // 3 2 1 1 1 4 printList(list); delect(list, 1); printList(list); // 3 2 1 1 4 delectAll(list, 1); // 3 2 4 printList(list); return 0; }