C语言创建双链表用尾插法,C实现头插法和尾插法来构建非循环双链表(不带头结点)(示例代码)...

在实际使用中,双链表比单链表方便很多,也更为灵活。对于不带头结点的非循环双链表的基本操作,我在《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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值