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

#include 
#include 

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;
}

/* 你的代码将被嵌在这里 */

List Read()
{
	
	List list = malloc(sizeof(PtrToNode));
	list->Next = NULL;
	List r = list;
	int n = 0;
	scanf("%d",&n);
	while(n--)
	{
		List p = malloc(sizeof(PtrToNode));
		scanf("%d",&p->Data);
		p->Next = r->Next;
		r->Next = p;
		r = p;
	}
	return list;
} 
void Print( List L )
{
	//system("pause");
	List p = L->Next;
	if(!L->Next)
	{
		printf("NULL");
	}
	else
	{
		while(p)
		{
		printf("%d ",p->Data);
		p = p->Next;
		}
		printf("\n");
	}
} 
List Merge( List L1, List L2 ){
    List r;
    //建立头结点而不能使用L1或L2的头结点是因为后边要将L1,L2置为NULL
    PtrToNode L = ( PtrToNode )malloc( sizeof( struct Node ) );
    List p=L1->Next;
    List q=L2->Next;
    r=L;
    L->Next=NULL;
    while(p!=NULL&&q!=NULL){
        if(p->DataData){
            r->Next=p;
            p=p->Next;
            r=r->Next;

        }
        else{
            r->Next=q;
            q=q->Next;
            r=r->Next;
        }

    }
    r->Next=NULL;
    r->next = p?p:q;
    L1->Next=NULL;
    L2->Next=NULL;
    return L;
}


你可能感兴趣的:(数据结构)