用C语言将两个单链表合并为一个单链表。
时间: 2024-06-13 22:09:11 浏览: 125
c语言实现两个单链表的交叉合并方式
5星 · 资源好评率100%
以下是C语言将两个单链表合并为一个单链表的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} SLNode;
// 创建单链表
SLNode *createList(int n) {
SLNode *head, *p, *q;
int i, num;
head = (SLNode *)malloc(sizeof(SLNode));
head->next = NULL;
q = head;
for (i = 0; i < n; i++) {
p = (SLNode *)malloc(sizeof(SLNode));
scanf("%d", &num);
p->data = num;
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
// 合并两个单链表
SLNode *merge(SLNode *head1, SLNode *head2) {
SLNode *p1, *p2, *p3, *head3;
p1 = head1->next;
p2 = head2->next;
head3 = (SLNode *)malloc(sizeof(SLNode));
head3->next = NULL;
p3 = head3;
while (p1 != NULL && p2 != NULL) {
if (p1->data <= p2->data) {
p3->next = p1;
p3 = p3->next;
p1 = p1->next;
} else {
p3->next = p2;
p3 = p3->next;
p2 = p2->next;
}
}
if (p1 != NULL) {
p3->next = p1;
}
if (p2 != NULL) {
p3->next = p2;
}
return head3;
}
// 输出单链表
void printList(SLNode *head) {
SLNode *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n, m;
SLNode *head1, *head2, *head3;
printf("请输入第一个单链表的长度:");
scanf("%d", &n);
printf("请输入第一个单链表的元素:");
head1 = createList(n);
printf("请输入第二个单链表的长度:");
scanf("%d", &m);
printf("请输入第二个单链表的元素:");
head2 = createList(m);
head3 = merge(head1, head2);
printf("合并后的单链表为:");
printList(head3);
return 0;
}
```
阅读全文