c语言链表末尾插入新结点
时间: 2023-09-29 11:10:08 浏览: 50
链表末尾插入新节点的基本思路是:
1. 遍历链表,找到最后一个结点。
2. 创建新结点,并将其插入到最后一个结点的 next 指针指向的位置。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 在链表末尾插入新节点
void insertAtEnd(struct Node** headRef, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*headRef == NULL) {
// 如果链表为空,新节点就是头结点
*headRef = newNode;
return;
}
struct Node* current = *headRef;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// 打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// 测试代码
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtEnd(&head, 4);
printf("链表内容:");
printList(head);
return 0;
}
```
输出结果为:
```
链表内容:1 2 3 4
```
其中,insertAtEnd() 函数是实现链表末尾插入新节点的关键部分。它接收一个指向链表头指针的指针 headRef,因为在函数中需要修改 headRef 指向的内容(即链表头指针)。函数中首先创建一个新节点,然后遍历链表找到最后一个结点,并将新节点插入到最后一个结点的 next 指针指向的位置。注意在链表为空时需要特殊处理。