1. 程式人生 > >連結串列實現(C語言)

連結串列實現(C語言)

  • C語言實現連結串列基本資料結構的基本操作
  • 參考《資料機構與演算法分析》
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef int ElementType;

struct Node
{
    ElementType Element;
    Position Next;
};

//連結串列頭結點的初始化,申請記憶體
//對每一個節點的指標只是指向記憶體的地址空間,要想使用這個節點,例如 //使用節點的資料域或者指標域都必須申請記憶體才能使用 Position Init() { Position head; head = (Position)malloc(sizeof(struct Node)); if (head == NULL) { printf("init failed!"); return NULL; } head->Next = NULL; return head; } Position Init() { Position head; head =
(Position)malloc(sizeof(struct Node)); if (head == NULL) { printf("init failed!"); return NULL; } head->Next = NULL; return head; } //傳入的List沒有被使用,之所以這麼做是因為實現其他的功能可能需要用到List void Insert(ElementType X, List L, Position P) { Position TmpCell; TmpCell = (Position)malloc(sizeof(struct Node)); if
(TmpCell == NULL) { printf("malloc space failed!"); return; } TmpCell->Element = X; TmpCell->Next = P->Next; P->Next = TmpCell; } //判斷條件使用 TmpNode != NULL,而不是使用TmpNode->next != NULL的原因 //是連結串列的實現沒有使用尾節點,要想輸出最後一個節點的資料就不能用後者 void PrintList(List L) { Position TmpNode = L->Next; while (TmpNode != NULL) { printf("%d\n", TmpNode->Element); TmpNode = TmpNode->Next; } } // 查詢X的位置,返回指標 Position Find(ElementType X, List L) { Position P = L->Next; while (P != NULL && P->Element != X) { P = P->Next; } return P; } //返回X的前一個元素的指標 Position FindPrevious(ElementType X, List L) { Position P = L; while (P->Next != NULL && P->Next->Element != X) { P = P->Next; } return P; } // 刪除X元素指標,釋放空間,對於不存在的元素什麼也不做 void Delete(ElementType X, List L) { Position P, TmpCell; P = FindPrevious(X, L); TmpCell = P->Next; P->Next = TmpCell->Next; free(TmpCell); } //列表頭結點初始化後才能使用 int main(int argc, char const *argv[]) { List L = Init(); Position TmpNode = L; for (int i = 0; i < 5; i++) { Insert(i, L, TmpNode); TmpNode = TmpNode->Next; } PrintList(L); // Position Tmp = FindPrevious(3, L); // printf("%d\n", Tmp->Element); Delete(3, L); PrintList(L); return 0; }