编写一个C语言代码,将两个递增的有序链表合并为一个递增的有序链表。要求结果链表仍使用原来两个链表的存储空间, 不另外占用其它的存储空间。表中不允许有重复的数据。
时间: 2024-03-25 20:31:40 浏览: 80
以下是C语言代码,实现将两个递增的有序链表合并为一个递增的有序链表,并且结果链表仍使用原来两个链表的存储空间,不另外占用其它的存储空间。表中不允许有重复的数据。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void merge(Node *p1, Node *p2) {
Node *p = p1->next;
Node *q = p2->next;
Node *r = p1; while (p && q) {
if (p->data <= q->data) {
r->next = p;
p = p->next;
} else {
r->next = q;
q = q->next;
}
r = r->next;
}
if (p) {
r->next = p;
} else {
r->next = q;
}
free(p2);
}
int main() {
Node *p1 = (Node *)malloc(sizeof(Node));
Node *p2 = (Node *)malloc(sizeof(Node));
p1->next = NULL;
p2->next = NULL;
Node *tail1 = p1;
Node *tail2 = p2;
int n, m;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
Node *node = (Node *)malloc(sizeof(Node));
node->data = x;
node->next = NULL;
tail1->next = node;
tail1 = node;
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int x;
scanf("%d", &x);
Node *node = (Node *)malloc(sizeof(Node));
node->data = x;
node->next = NULL;
tail2->next = node;
tail2 = node; }
merge(p1, p2);
Node *p = p1->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
return 0;
}
```
阅读全文