程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> C實現頭插法和尾插法來構建單鏈表(帶頭結點)

C實現頭插法和尾插法來構建單鏈表(帶頭結點)

編輯:關於C

我在之前一篇博客《C實現頭插法和尾插法來構建單鏈表(不帶頭結點)》中詳細實現了如何使用頭插法和尾插法來建立一個不帶頭結點的單鏈表,但是在實際使用中,我們用的最多的還是帶頭結點的單鏈表。今天我們就來實現一下帶頭結點鏈表的頭插和尾插。

核心代碼如下:

//創建帶頭結點的單鏈表(尾插法)
void CreateListTailInsert(Node *pNode){

    /**
     *  就算一開始輸入的數字小於等於0,帶頭結點的單鏈表都是會創建成功的,只是這個單鏈表為空而已,也就是裡面除了頭結點就沒有其他節點了。
     */
    Node *pInsert;
    Node *pMove;
    pInsert = (Node *)malloc(sizeof(Node));//需要檢測分配內存是否成功 pInsert == NULL  ?
    memset(pInsert, 0, sizeof(Node));
    pInsert->next = NULL;

    scanf("%d",&(pInsert->element));
    pMove = pNode;
    while (pInsert->element > 0) {

        pMove->next = pInsert;
        pMove = pInsert;//pMove始終指向最後一個節點

        pInsert = (Node *)malloc(sizeof(Node)); //需要檢測分配內存是否成功 pInsert == NULL  ?
        memset(pInsert, 0, sizeof(Node));
        pInsert->next = NULL;

        scanf("%d",&(pInsert->element));
    }

    printf("%s函數執行,帶頭結點的單鏈表使用尾插法創建成功\n",__FUNCTION__);
}

//創建帶頭結點的單鏈表(頭插法)
void CreateListHeadInsert(Node *pNode){

    Node *pInsert;
    pInsert = (Node *)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));
    pInsert->next = NULL;

    scanf("%d",&(pInsert->element));
    while (pInsert->element > 0) {
        pInsert->next = pNode->next;
        pNode->next = pInsert;

        pInsert = (Node *)malloc(sizeof(Node));
        memset(pInsert, 0, sizeof(Node));
        pInsert->next = NULL;

        scanf("%d",&(pInsert->element));
    }

    printf("%s函數執行,帶頭結點的單鏈表使用頭插法創建成功\n",__FUNCTION__);
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved