#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;