
在上一篇博客“ 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__);
}

原始链接:
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-199248-1.html
哈哈----经济学家算帐只算好的一面
解决就业等