首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言帶頭尾節點雙向非循環鏈表全操作集:創建、遍歷、增刪改查完整庫

     編輯:關於C語言

節點定義

typedef int ElemType;
typedef struct Node {
    ElemType data;
    struct Node *prev, *next;
} Node;

核心操作函數速查表

函數功能關鍵邏輯
InitList初始化分配頭尾哨兵,head->next=tail, tail->prev=head
CreateList尾插建表輸入>0 循環插入尾哨兵前
PrintList正序打印p=head->next; while(p!=tail)
PrintReverse逆序打印p=tail->prev; while(p!=head)
ClearList清空依次 free head->next 直到遇到 tail
SizeList長度遍歷計數
IsEmpty判空head->next == tail
GetElement按位置取值遍歷到 pos 返回 data
GetElemAddr按值找地址遍歷匹配返回 &node->data
ModifyElem修改位置值遍歷到 pos 賦新值
InsertHead頭插新節點夾在 head 與 head->next 間
InsertTail尾插新節點夾在 tail->prev 與 tail 間

關鍵代碼片段:頭插與尾插

// 頭插
void insertHead(Node *head, Node *tail, int x) {
    Node *n = malloc(sizeof(Node));
    n->data = x;
    n->prev = head;
    n->next = head->next;
    head->next->prev = n;
    head->next = n;
}

// 尾插
void insertTail(Node *head, Node *tail, int x) {
    Node *n = malloc(sizeof(Node));
    n->data = x;
    n->next = tail;
    n->prev = tail->prev;
    tail->prev->next = n;
    tail->prev = n;
}

測試主程序

int main() {
    Node *head, *tail;
    InitList(&head, &tail);
    CreateList(head, tail); // 輸入: 1 2 3 0
    PrintList(head, tail);  // 1 2 3
    PrintReverse(head, tail); // 3 2 1
    InsertHead(head, tail, 100);
    InsertTail(head, tail, 900);
    PrintList(head, tail);  // 100 1 2 3 900
    ClearList(head, tail);
    PrintList(head, tail);  // (空行)
    return 0;
}

設計優勢總結

  • 統一了首尾/中間/空表的操作邏輯,無需特判。
  • 雙向鏈接使逆序遍歷、尾部操作同樣高效。
  • 哨兵節點簡化邊界條件,代碼健壯性大幅提升。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved