405人阅读 评论(0)

# 题目描述

02-线性结构1 两个有序链表序列的合并 (15分)

List Merge( List L1, List L2 );

typedef struct Node *PtrToNode;
struct Node {
ElementType Data; /* 存储结点数据 */
PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L1和L2是给定的带头结点的单链表，其结点存储的数据是递增有序的；函数Merge要将L1和L2合并为一个递增的整数序列。应直接使用原序列中的结点，返回归并后的链表头指针。

#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode   Next;
};
typedef PtrToNode List;
void Print( List L ); /* 细节在此不表；空链表将输出NULL */
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
/* 你的代码将被嵌在这里 */


3
1 3 5
5
2 4 6 8 10

1 2 3 4 5 6 8 10
NULL
NULL

List Test(List L){
List temp,LL;
temp = L;
LL = (List)malloc(sizeof(struct Node));
L = L->Next;
LL->Next = L;
while( L ){
temp->Next = L->Next;
L = L->Next;
}
return LL;
}

void Test2(List L){
while( L ){
L = L->Next;
}
}

# AC代码：

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode   Next;
};
typedef PtrToNode List;

void Print( List L ); /* 细节在此不表；空链表将输出NULL */

List Merge( List L1, List L2 );

int main()
{
List L1, L2, L;

Print(L1);
Print(L2);

printf("\n");

L = Merge(L1, L2);

Print(L);
Print(L1);
Print(L2);

return 0;
}

List L = (List)malloc(sizeof(struct Node));
L->Next = NULL; //L为头结点
List tmp = L;
ElementType x;
while(scanf("%d",&x),x!=-1){
List TempL = (List)malloc(sizeof(struct Node));
TempL->Data = x;
TempL->Next = NULL;
tmp->Next = TempL;
tmp = tmp->Next;
}
return L;
}

/* Print */
void Print( List L ){
List Temp = L->Next;
if( L->Next == NULL ){
printf("NULL\n");
return;
}else{
while( Temp ){
printf("%d ",Temp->Data);
Temp = Temp->Next;
}
printf("\n");
}
}

/* 你的代码将被嵌在这里 */
List Merge(List L1, List L2){
if( L1->Next == NULL){
List temp,L;
L = (List)malloc(sizeof(struct Node));
temp = L2;
L2 = L2->Next;
L->Next = L2;
while( L2 ){
temp->Next = L2->Next;
L2 = L2->Next;
}
return L;
}else if( L2->Next == NULL){
List temp,L;
L = (List)malloc(sizeof(struct Node));
temp = L1;
L1 = L1->Next;
L->Next = L1;
while( L1 ){
temp->Next = L1->Next;
L1 = L1->Next;
}
return L;
} else{
List LL = (List)malloc(sizeof(struct Node));
List LLL = LL;
List temp1,temp2;
temp1 = L1; temp2 = L2;
L1 = L1->Next; L2 = L2->Next;
while( L1 && L2){
if(L1->Data < L2->Data){
LL->Next = L1;
LL = LL->Next;
temp1->Next = L1->Next;
L1 = L1->Next;
}else{
LL->Next = L2;
LL = LL->Next;
temp2->Next = L2->Next;
L2 = L2->Next;
}
}
while( L1 ){
LL->Next = L1;
LL = LL->Next;
temp1->Next = L1->Next;
L1 = L1->Next;
}
while(L2){
LL->Next = L2;
LL = LL->Next;
temp2->Next = L2->Next;
L2 = L2->Next;
}
return LLL;
}
}


THE END.

个人资料
等级：
访问量： 5万+
积分： 1964
排名： 2万+
最新评论