已知两个非降序链表序列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
#include <stdio.h>
#include <stdlib.h>
struct node {
int Data;
struct node *Next;
};
struct node *creatNode();
struct node *listAdd(struct node *head_1, struct node *head_2);
int main(){
struct node *L1 = creatNode();
struct node *L2 = creatNode();
struct node *L3 = listAdd(L1, L2);
struct node *flag = L3;
if(flag == NULL) printf("NULL");
else{
while(flag->Data != -1){
printf("%d",flag->Data);
flag = flag->Next;
if(flag->Data != -1) printf(" ");
}
}
return 0;
}
struct node* creatNode(){
struct node *head = (struct node*)malloc(sizeof(struct node));
struct node *flag;
flag = head;
scanf("%d",&flag->Data);
while(flag->Data != -1){
flag->Next = (struct node*)malloc(sizeof(struct node));
flag = flag->Next;
scanf("%d",&flag->Data);
}
flag->Next = NULL;
return head;
}
struct node *listAdd(struct node *head_1, struct node *head_2){
struct node *addHead = (struct node*)malloc(sizeof(struct node));
struct node *addFlag = addHead;
while(head_1->Data != -1 && head_2->Data != -1){
if(head_1->Data <= head_2->Data){
addFlag->Next = head_1;
head_1 = head_1->Next;
addFlag->Next->Next = NULL;
addFlag = addFlag->Next;
}
if(head_1->Data >= head_2->Data){
addFlag->Next = head_2;
head_2 = head_2->Next;
addFlag->Next->Next = NULL;
addFlag = addFlag->Next;
}
}
if(head_1->Data != -1){
addFlag->Next = head_1;
}
if(head_2->Data != -1){
addFlag->Next = head_2;
}
addHead = addHead->Next;
return addHead;
}