02-线性结构1 两个有序链表序列的合并 (15分)
本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个递增的整数序列。
函数接口定义:
List Merge( List L1, List L2 );
其中List
结构定义如下:
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;
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表;空链表将输出NULL */
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
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
<pre style="margin-top: 0px; margin-bottom: 0px; color: rgb(51, 51, 51); padding: 6px 12px; border: 1px solid rgb(221, 221, 221); word-break: break-word; background-color: rgb(247, 247, 247);">//两个链表各有一个游标,用来遍历对比两个链表的当前元素,小的那个加入新链表,游标继续往后,另一个不变;<p></p><p><span style="font-family: 'YaHei consolas Hybrid', Consolas;">//遍历完,判断是否两个链表有没有均遍历到头</span></p>
List Merge( List L1, List L2 )
{
List temp1=L1->Next;
List temp2=L2->Next;
List p;
p=(List)malloc(sizeof(struct Node));
p->Next=NULL;
List temp=p;
while(temp1&&temp2){
if(temp1->Data<temp2->Data){
temp->Next=temp1;
temp1=temp1->Next;
temp=temp->Next;
}
else{
temp->Next=temp2;
temp2=temp2->Next;
temp=temp->Next;
}
}
while(temp1!=NULL){
temp->Next=temp1;
temp1=temp1->Next;
temp=temp->Next;
}
while(temp2!=NULL){
temp->Next=temp2;
temp2=temp2->Next;
temp=temp->Next;
}
L1->Next=NULL;
L2->Next=NULL;
temp->Next=NULL;
return p;
}