在實際使用中,雙鏈表比單鏈表方便很多,也更為靈活。對於不帶頭結點的非循環雙鏈表的基本操作,我在《C語言實現雙向非循環鏈表(不帶頭結點)的基本操作》這篇文章中有詳細的實現。今天我們就要用兩種不同的方式頭插法和尾插法來建立雙鏈表。
核心代碼如下:
//尾插法創建不帶頭結點的非循環雙向鏈表 Node *TailInsertCreateList(Node *pNode){ Node *pInsert; Node *pMove; pInsert = (Node*)malloc(sizeof(Node)); memset(pInsert, 0, sizeof(Node)); pInsert->next = NULL; pInsert->prior = NULL; scanf("%d",&(pInsert->element)); pMove = pNode; if (pInsert->element <= 0) { printf("%s函數執行,輸入數據非法,建立鏈表停止\n",__FUNCTION__); return NULL; } while (pInsert->element > 0) { if (pNode == NULL) { pNode = pInsert; pMove = pNode; }else{ pMove->next = pInsert; pInsert->prior = pMove; pMove = pMove->next; } pInsert = (Node *)malloc(sizeof(Node)); memset(pInsert, 0, sizeof(Node)); pInsert->next = NULL; pInsert->prior = NULL; scanf("%d",&(pInsert->element)); } printf("%s函數執行,尾插法建立鏈表成功\n",__FUNCTION__); return pNode; } //頭插法創建不帶頭結點的非循環雙向鏈表 Node *HeadInsertCreateList(Node *pNode){ Node *pInsert; pInsert = (Node *)malloc(sizeof(Node)); memset(pInsert, 0, sizeof(Node)); pInsert->next = NULL; pInsert->prior = NULL; scanf("%d",&(pInsert->element)); if (pInsert->element <= 0) { printf("%s函數執行,輸入數據非法,建立鏈表停止\n",__FUNCTION__); return NULL; } while (pInsert->element > 0) { if (pNode == NULL) { pNode = pInsert; }else{ pInsert->next = pNode; pNode->prior = pInsert; pNode = pInsert; } pInsert = (Node *)malloc(sizeof(Node)); memset(pInsert, 0, sizeof(Node)); pInsert->next = NULL; pInsert->prior = NULL; scanf("%d",&(pInsert->element)); } printf("%s函數執行,頭插法建立鏈表成功\n",__FUNCTION__); return pNode; }