目录
作业5-链表
剩余时间: 4天 04:32:31
7-1 两个有序链表序列的合并 (20 分)
已知两个非降序链表序列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
算法1:用Create函数连续输入(更快)
//库函数头文件包含
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int Status;
typedef int ElemType; //假设线性表中的元素均为整型
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
void CreateLinkList(LinkList &L)
{
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
LinkList temp1=L;
while(1)
{
LinkList temp2;
temp2=(LinkList)malloc(sizeof(LNode));
scanf("%d",&temp2->data);
if(-1==temp2->data){free(temp2);break;}
temp2->next=temp1->next;
temp1->next=temp2;
temp1=temp1->next;
}
temp1->next=NULL;
}
void PlusLinkList(LinkList a,LinkList b,LinkList &c)
{
c=(LinkList)malloc(sizeof(LNode));
c->next=NULL;
LinkList pa=a->next,pb=b->next,pc=c;
while(pa&&pb)
{
if(pa->data<=pb->data){pc->next=pa;pc=pc->next;pa=pa->next;}
else {pc->next=pb;pc=pc->next;pb=pb->next;}
}
if(pa){pc->next=pa;}
else {pc->next=pb;}
}
void PrintList(LinkList L);
void PrintList(LinkList L)
{
LinkList temp=L->next;
if(!temp){printf("NULL");}
while(temp)
{
printf("%d",temp->data);
if(temp->next){printf(" ");}
temp=temp->next;
}
}
int main()
{
LinkList L,M,sum;
CreateLinkList(L);
CreateLinkList(M);
PlusLinkList(L,M,sum);
PrintList(sum);
}
算法2: 用push_back函数分别填入(更灵活)
//库函数头文件包含
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *front,*next;
}LNode,*LinkList;
void CreateLinkList(LinkList &L);
void CreateLinkList(LinkList &L)
{
L=(LinkList)malloc(sizeof(LNode));
L->front=L;
L->next=L;
}
void push_back(LinkList &L,int e);
void push_back(LinkList &L,int e)
{
LinkList temp;
temp=(LinkList)malloc(sizeof(LNode));
temp->data=e;
temp->next=L;
temp->front=L->front;
L->front->next=temp;
L->front=temp;
}
void PlusLinkList(LinkList a,LinkList b,LinkList &c)
{
c=(LinkList)malloc(sizeof(LNode));
c->next=c->front=c;
LinkList pa=a->next,pb=b->next,pc=c;
while(pa!=a&&pb!=b)
{
if(pa->data<=pb->data){pc->next=pa;pc->next->front=pc;pc=pc->next;pa=pa->next;}
else {pc->next=pb;pc->next->front=pc;pc=pc->next;pb=pb->next;}
}
if(pa!=a){pc->next=pa;pc->next->front=pc;c->front=a->front;c->front->next=c;}
else {pc->next=pb;pc->next->front=pc;c->front=b->front;c->front->next=c;}
}
void PrintList(LinkList &L);
void PrintList(LinkList &L)
{
LinkList temp=L->next;
if(temp==L){printf("NULL");}
while(temp!=L)
{
printf("%d",temp->data);
if(temp->next!=L){printf(" ");}
temp=temp->next;
}
}
int main()
{
LinkList L,M,sum;
int t;
CreateLinkList(L);
while(1)
{
scanf("%d",&t);
if(t==-1){break;}
push_back(L,t);
}
CreateLinkList(M);
while(1)
{
scanf("%d",&t);
if(t==-1){break;}
push_back(M,t);
}
PlusLinkList(L,M,sum);
PrintList(sum);
}