标签:
在实际使用中,双链表比单链表方便很多,也更为灵活。对于不带头结点的非循环双链表的基本操作,我在《C语言实现双向非循环链表(不带头结点)的基本操作》这篇文章中有详细的实现。今天我们就要用两种不同的方式头插法和尾插法来建立双链表。代码上传至 https://github.com/chenyufeng1991/HeadInsertAndTailInsertDoubleList 。
核心代码如下:
//尾插法创建不带头结点的非循环双向链表 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; }
标签:
原文地址:http://blog.csdn.net/chenyufeng1991/article/details/50787987