雙向鏈表也叫雙鏈表,它的每個數據節點中都有兩個指針,分別指向直接後繼和直接前驅。所以,從雙向鏈表中的任何一個節點開始,都可以很方便的訪問它的前驅結點和後繼節點。別人常常來構造雙向循環鏈表,今天我們特立獨行一下,先來嘗試構造雙向非循環鏈表。示例代碼上傳至 https://github.com/chenyufeng1991/DoubleLinkedList 。
構造節點:
typedef struct NodeList{ int element; struct NodeList *prior; struct NodeList *next; }Node;
//創建非循環雙向鏈表 Node *createList(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; }