#include <stdlib.h> #include <stdio.h> #define MAX 10 struct List { int Number; int Total; struct List *Next; }; typedef struct List Node; typedef Node * Link; int Data[2][MAX]={1,3,5,7,2,4,6,8,9,10, 15,35,10,67,25,65,38,70,30,20}; Link Delete_List(Link Head,int key) { Link Pointer = Head; Link back; while(1){ if(Pointer->Next == NULL){ printf("Not found\n"); break; } if(Head->Number == key){ Head = Pointer->Next; free(Pointer); break; } back = Pointer; Pointer = Pointer->Next; if(Pointer->Number == key){ back->Next = Pointer->Next; if(Pointer->Number == key){ back->Next = Pointer->Next; free(Pointer); break; } } } return Head; } void Print_List(Link Head) { Link Pointer = Head; while(Pointer != NULL){ printf("[%d,%d]",Pointer->Number,Pointer->Total); Pointer = Pointer->Next; } printf("\n"); } void Free_List(Link Head) { Link Pointer; while(Head != NULL){ Pointer = Head; Head = Head->Next; free(Pointer); } } Link Create_List(Link Head) { Link New; Link Pointer; int i; Head = (Link)malloc(sizeof(Node)); if(Head == NULL){ printf("記憶體分配失敗\n"); }else{ Head->Number = Data[0][0]; Head->Total = Data[1][0]; Head->Next = NULL; Pointer = Head; for(i=1; i<MAX; i++){ New = (Link)malloc(sizeof(Node)); New->Number = Data[0][i]; New->Total = Data[1][i]; New->Next = NULL; Pointer->Next = New; Pointer = New; } } return Head; } void main() { Link Head; int key; Head = Create_List(Head); if(Head != NULL){ Print_List(Head); while(1){ printf("Input 0 to Exit\n"); printf("請輸入數值:"); scanf("%d",&key); if(key == 0) break; Head = Delete_List(Head,key); Print_List(Head); } Free_List(Head); } }
參考資料:
資料結構 黃國瑜/葉乃菁