#include<stdio.h> #include<stdlib.h> typedef struct { int data; struct Node* next; }Node; Node* initList(){ 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 tailInsert(Node* list, int data) { Node* head = list;//保存头节点 Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->next = NULL; list = list->next; while (list->next) { list = list->next; } list->next = node; list = head; list->data++; } //删除 void delete(Node* list, int data) { Node* pre = list; Node* current = list->next; while (current) { if (current->data == data) { pre->next = current->next; free(current); break;//假设没有重复的该数据 } pre = current; current = current->next; } list->data--; } //打印 void printList(Node* list) { list = list->next; while (list) { printf("%d ", list->data); list = list->next; } printf("\n"); } int main() { Node* list = initList(); headInsert(list, 1); headInsert(list, 2); headInsert(list, 3); headInsert(list, 4); headInsert(list, 5); tailInsert(list, 6); tailInsert(list, 7); tailInsert(list, 8); tailInsert(list, 9); printList(list); delete(list, 5); delete(list, 9); delete(list, 6); printList(list); return 0; }
02-14
1706
06-27
10-23
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交