Exercises in the data structure of the title (English II) Problem 2.5 merge two ordered sequence list (15 minutes)

This problem required to achieve a function, the incremented sequence of integers represented by two lists combined into a non-decreasing sequence of integers.

Function interface definition:

List Merge( List L1, List L2 );

Wherein the Liststructure is defined as follows:

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

L1And L2a single list lead given node, the node storing data which is incremented ordered; functions MergeTo L1and L2combined into a non-decreasing sequence of integers. Should be used as the original node sequence, returns the head pointer list after node lead merged.

Referee test program Example:

#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; } /* 你的代码将被嵌在这里 */ 

Sample input:

3
1 3 5
5
2 4 6 8 10

Sample output:

1 2 3 4 5 6 8 10 
NULL
NULL



List Merge(List L1,List L2){
    List p1=L1,p2=L2;
    L1=L1->Next;L2=L2->Next;
    List res=(List)malloc(sizeof(List));
    List tmp=res;
    while(L1!=NULL&&L2!=NULL){
        if((L1->Data)<(L2->Data)){
            tmp->Next=L1;
            L1=L1->Next;
            tmp=tmp->Next;
        }else{
            tmp->Next=L2;
            L2=L2->Next;
            tmp=tmp->Next;
        }
    }
    if(L1!=NULL) tmp->Next=L1;
    if(L2!=NULL) tmp->Next=L2;
    p1->Next=NULL;
    p2->Next=NULL;
    return res;
}

Note that the point of the question, led the list pointer

Guess you like

Origin www.cnblogs.com/littlepage/p/11616616.html
Recommended