c语言链表 写一个程序如果头链表不为空在头链表后输入新的链表
时间: 2024-01-04 15:18:37 浏览: 25
以下是C语言链表写一个程序如果头链表不为空在头链表后输入新的链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 在头结点后插入新结点
void insertAtEnd(struct Node** head_ref, int new_data) {
// 分配新结点的内存
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;
// 设置新结点的数据
new_node->data = new_data;
new_node->next = NULL;
// 如果链表为空,则将新结点设置为头结点
if (*head_ref == NULL) {
*head_ref = new_node; return;
}
// 遍历链表,找到最后一个结点
while (last->next != NULL) {
last = last->next;
}
// 将新结点插入到最后一个结点的后面
last->next = new_node;
return;
}
// 打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
// 初始化链表头结点
struct Node* head = NULL;
// 在头结点后插入新结点
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
// 打印链表
printf("链表内容为:");
printList(head);
return 0;
}
```