c语言在尾部添加新节点,在单链表最后插入节点

本文介绍了如何在C语言中向单链表的尾部添加新节点,包括处理空链表和非空链表的情况。通过示例代码详细展示了节点插入的过程,并提供了用户交互式的程序实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要在单链表的最后插入节点,需要提及以下两种情况。

新节点添加到空链表中

新节点添加到链表的末尾

1. 新节点添加到空链表中

如果满足条件(head == NULL)。 因此,只需要在C语言中使用malloc语句为新节点分配空间。数据和节点的链接部分通过使用以下语句来设置。

ptr->data = item;

ptr -> next = NULL;

因为,ptr是插入链表中的唯一节点,因此需要使链表的头指针指向这个新节点,通过使用以下语句来完成。

Head = ptr

2. 新节点添加到链表的末尾

如果条件head = NULL失败,因为head不为null。需要声明一个临时指针temp才能遍历链表。temp指向链表的第一个节点。

temp = head

然后,使用以下语句遍历整个链表:

while (temp -> next != NULL){

temp = temp -> next;

}

在循环结束时,temp将指向链表的最后一个节点。 现在,为新节点分配空间,并将项目分配给其数据部分。 因为,新节点将成为链表的最后一个节点,因此新节点下一链接部分需要指向null。 使temp节点的下一链接部分(当前是链表的最后一个节点)指向新节点(ptr)。

temp = head;

while (temp -> next != NULL)

{

temp = temp -> next;

}

temp->next = ptr;

ptr->next = NULL;

算法

第1步:IF PTR = NULL

写OVERFLOW

转到第1步

[结束]

第2步:设置NEW_NODE = PTR

第3步:SET PTR = PTR - > NEXT

第4步:设置NEW_NODE - > DATA = VAL

第5步:设置NEW_NODE - > NEXT = NULL

第6步:设置PTR = HEAD

第7步:重复第8步,同时PTR - > NEXT != NULL

第8步:SET PTR = PTR - > NEXT

[循环结束]

第9步:SET PTR - > NEXT = NEW_NODE

第10步:退出

e1bdd4d38332d11fe6b082c6c19704ba.png

C语言示例代码 -

#include

#include

void lastinsert(int);

struct node

{

int data;

struct node *next;

};

struct node *head;

void main()

{

int choice, item;

do

{

printf("\nEnter the item which you want to insert?\n");

scanf("%d", &item);

lastinsert(item);

printf("\nPress 0 to insert more ?\n");

scanf("%d", &choice);

} while (choice == 0);

}

void lastinsert(int item)

{

struct node *ptr = (struct node*)malloc(sizeof(struct node));

struct node *temp;

if (ptr == NULL)

{

printf("\nOVERFLOW");

}

else

{

ptr->data = item;

if (head == NULL)

{

ptr->next = NULL;

head = ptr;

printf("\nNode inserted");

}

else

{

temp = head;

while (temp->next != NULL)

{

temp = temp->next;

}

temp->next = ptr;

ptr->next = NULL;

printf("\nNode inserted");

}

}

}

执行上面代码,得到类似下面的结果 -

Enter the item which you want to insert?

12

Node inserted

Press 0 to insert more ?

0

Enter the item which you want to insert?

23

Node inserted

Press 0 to insert more ?

2

¥ 我要打赏

纠错/补充

收藏

上一篇:链表

下一篇:双链表

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值