單鏈表的函式宣告和定義
阿新 • • 發佈:2018-11-03
#include<stdio.h> #include<stdlib.h> typedef int ElemType; typedef struct node { ElemType data; struct node *next; }Node; typedef Node* PtrToNode; typedef PtrToNode List; typedef PtrToNode Position; //判斷是否是空連結串列 int IsEmpty(List L) { return L->next == NULL; } //判斷是否是末尾 int IsLast(Position P, List L) { return P->next == NULL; } //尋找 Position Find(ElemType X, List L) { Position P; P = L->next; while (P != NULL && P->data != X) { P = P->next; } return P; } Position FindPrevious(ElemType X, List L) { Position P; P = L; while (P->next != NULL && P->next->data != X) { P = P->next; } return P; } void Delete(ElemType X, List L) { Position P, Tmp; P = FindPrevious(X, L); if (!IsLast(P,L)) { Tmp = P->next; P->next = Tmp; free(Tmp); } } //根據位置來插入元素 void InSert(ElemType X, List L, Position P) { Position TmpCell; TmpCell = (List)malloc(sizeof(Node)); if (TmpCell == NULL) { printf("Out of space!!!"); } TmpCell->data = X; TmpCell->next = P->next; P->next = TmpCell; } //輸出連結串列 void PrintList(List L) { Position P; P = L; while (P != NULL) { printf("%d ", P->data); P = P->next; } printf("\n"); } //建立連結串列 List CreatedList() { Position head, p1, p2; int n; p2 = p1 = (Node*)malloc(sizeof(Node)); if (p1 == NULL) { printf("Can not create p1!!!"); return NULL; } else { head = NULL; n = 0; printf("請輸入資料:"); scanf_s("%d", &(p1->data)); while (p1->data != 0) { n++; if (n == 1) { head = p1; p2->next = NULL; } else { p2->next = p1; } p2 = p1; p1 = (struct node*)malloc(sizeof(struct node)); printf("請輸入資料:"); scanf_s("%d", &(p1->data)); } p2->next = NULL; free(p1); p1 = NULL; return head; } } //刪除連結串列 void DeLeteList(List L) { Position P, Tmp; P = L->next; L->next = NULL; while (P != NULL) { Tmp = P->next; free(P); P = Tmp; } } //生成空連結串列 List MakeEmpty(List L) { L = (struct node*)malloc(sizeof(struct node)); L->data = 0; L->next = NULL; return L; } //返回頭結點 Position Header(List L) { return L; } //返回第一個資料節點的位置 Position First(List L) { if (L->next != NULL) return L->next; } //獲得位置P後繼節點位置 Position Advance(Position P) { if (P != NULL) return P->next; } //返回P位置的資料 ElemType Retrieve(Position P) { if (P != NULL) return P->data; }