连接两个单链表的简单c语言代码
时间: 2023-05-19 11:06:27 浏览: 57
以下是连接两个单链表的简单 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
struct Node* concatenate(struct Node* head1, struct Node* head2) {
if (head1 == NULL) {
return head2;
}
if (head2 == NULL) {
return head1;
}
struct Node* ptr = head1;
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = head2;
return head1;
}
int main() {
struct Node* head1 = NULL;
struct Node* head2 = NULL;
push(&head1, 3);
push(&head1, 2);
push(&head1, 1);
push(&head2, 6);
push(&head2, 5);
push(&head2, 4);
printf("List 1: ");
printList(head1);
printf("\nList 2: ");
printList(head2);
head1 = concatenate(head1, head2);
printf("\nConcatenated list: ");
printList(head1);
return 0;
}
```
这个程序定义了一个 `Node` 结构体,其中包含一个整数数据和一个指向下一个节点的指针。`printList` 函数用于打印链表中的所有元素。`push` 函数用于在链表的开头插入一个新节点。`concatenate` 函数用于连接两个链表,返回连接后的链表的头节点。在 `main` 函数中,我们创建了两个链表,将它们连接起来,并打印结果。