已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
代码:
/*
@两个有序链表序列的合并
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct List{
int data;
struct List *next;
}List,*list;
void ListInit(list &L){
list p = (list)malloc(sizeof(List));
L = p;
}
list CreatList(){
list head = (list)malloc(sizeof(list));
head->next = NULL;
list p,t;
int a ;
scanf("%d",&a);
if(a==-1){
return NULL;
}
else{
while(true){
if(a!=-1){
t=(list)malloc(sizeof(struct List));
t->data=a;
if(head->next==NULL){
head->next = t;
}
else{
p->next=t;
}
p=t;
}
else{
p->next=NULL; //一定要有此部分结束,否则传值无底线
break;
}
scanf("%d",&a);
}
return head;
}
}
int Lengthlist(list &L){
list p = L->next;
int length = 0;
while(p){
length++;
p = p->next;
}
return length;
}
list MergeList(list a,list b){ //合并两链表且不含重复元素
list la = a->next,lb = b->next;
list c,lc;
lc = c = a; //lc取a的地址
while(la&&lb){
if(la->data<=lb->data){
c->next = la ; c = la; la = la->next;
}
else{
c->next = lb; c = lb; lb = lb->next;
}
}
c->next = la?la:lb;
return lc; // 返回新表c的头节点
}
void PrintList(list &L){
list p = L->next;
int flag = 0;
while(p!=NULL){
if(!flag){
printf("%d",p->data);
flag = 1;
}
else{
printf(" %d",p->data);
}
p = p->next;
}
}
int main(int argc, char** argv) {
list d;
ListInit(d);
list a = CreatList(); //a链表
list b = CreatList(); //b链表
if(!a&&!b){
printf("NULL\n");
}
else{
d = MergeList(a,b);
PrintList(d);
}
return 0;
}
该博客介绍如何合并两个非降序链表S1和S2,形成一个新的非降序链表S3。输入和输出格式分别给出,内容涉及链表操作和排序。
1万+

被折叠的 条评论
为什么被折叠?



