我在之前一篇博客《C实现头插法和尾插法来构建单链表(不带头结点)》中具体实现了怎样使用头插法和尾插法来建立一个不带头结点的单链表,可是在实际使用中。我们用的最多的还是带头结点的单链表。今天我们就来实现一下带头结点链表的头插和尾插。
代码上传至 https://github.com/chenyufeng1991/HeadInsertAndTailInsert_HeadNode 。
//创建带头结点的单链表(尾插法)
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__);
}