两个有序链表序列的合并
题目要求如下:
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
C语言code:
#include <stdio.h>
#include <stdlib.h>
struct lian { //定义链表结构
int data; //数据区
struct lian *next; //指向自身的结构指针
};
struct lian *Randlian() //创建链表
{
int x;
struct lian *h, *s, *p;
p = (struct lian *)malloc(sizeof(struct lian));
s = (struct lian *)malloc(sizeof(struct lian));
h = NULL;
scanf("%d", &x);
if(x != -1) {
h = s;
}
while(x != -1) {
p = s;
s->data = x;
s = (struct lian *)malloc(sizeof(struct lian));
p->next = s;
scanf("%d", &x);
}
p->next = NULL;
return h;
}
struct lian *Addlian(struct lian *l1, struct lian *l2) //合并链表
{
struct lian *head, *h1, *h2, *p, *s1, *s2;
h1 = s1 = l1;
h2 = s2 = l2;
head = NULL;
if((s1 != NULL) && (s2 == NULL)) {
head = h1;
}
else if((s1 == NULL) && (s2 != NULL)) {
head = h2;
}
else if(s1 != NULL && s2 != NULL) {
if(s1->data < s2->data) {
head = h1;
p = s1;
s1 = p->next;
}
else {
head = h2;
p = s2;
s2 = p->next;
}
while(1) {
if(s1->data < s2->data) {
p->next = s1;
p = s1;
s1 = p->next;
if(s1 == NULL) {
p->next = s2;
break;
}
}
else{
p->next = s2;
p = s2;
s2 = p->next;
if(s2 == NULL) {
p->next = s1;
break;
}
}
}
}
return head;
}
void Putlian(struct lian *l) //打印新链表
{
struct lian *p;
p = l;
if(p != NULL){
printf("%d", p->data);
p = p->next;
while(p) {
printf(" %d", p->data);
p = p->next;
}
}
else {
printf("NULL");
}
}
int main(void)
{
struct lian *h1, *h2;
h1 = Randlian();
h2 = Randlian();
Putlian(Addlian(h1, h2));
return 0;
}