#include <stdio.h> #include <stdlib.h> typedef struct nodeList { int data; //数据域 struct nodeList *next; //指针域 } nodeList; //遍历链表 void TraverseList(struct nodeList *head) { while(head != NULL){ printf("%d \n",head->data); head=head->next; } } //头插法 nodeList *HeadCreatList(struct nodeList *head, int n) { struct nodeList *node; for (int i = 0; i < n; ++i) { node=(struct nodeList *)malloc(sizeof(struct nodeList)); node->data = i; node->next = head->next; head->next = node; } head->data = n; return head; } //尾插法 nodeList *TailCreatList(struct nodeList *head, int n) { struct nodeList *node,*end; end = head; for (int i = 0; i < n; ++i) { node=(struct nodeList *)malloc(sizeof(struct nodeList)); node->data = i; end->next = node; end = node; } head->data = n; return head; } //删除某个值 nodeList *deleteFromList(struct nodeList *head, int target) { struct nodeList *pre,*tmp; int count=0; tmp = head; pre = head; head= head->next; while(head != NULL){ if (head->data == target){ pre->next = head->next; count--; }else{ pre = head; count++; } head= head->next; } tmp->data = count; return tmp; } int main() { struct nodeList *head,*node; head=(struct nodeList *)malloc(sizeof(struct nodeList)); //头结点 //head->data = NULL; head->next = NULL; //头插法 head = HeadCreatList(head, 5); printf("头插法: \n"); TraverseList(head); //尾插法 head = TailCreatList(head, 5); printf("尾插法: \n"); TraverseList(head); //删除 head = deleteFromList(head,2); printf("删除2: \n"); TraverseList(head); return 0; }
执行结果:node
头插法,新结点始终在头结点以后,核心在于:spa
node->data = i; node->next = head->next; head->next = node;
尾插法,新结点始终在尾结点以后,核心在于:指针
node->data = i; end->next = node; end = node;