Experimental data structure --- merging two lists nondecreasing

description

Given two sequences incrementing integers A and B, showing the use of chain sequences A and B, and A and B are combined into an ascending ordered sequence C, C sequence does not allow duplicate data. Requires space complexity is O (1).

Entry

A plurality of sets of data, each set of three lines of data, a first behavior sequence length n and m A and B, the behavior of a second sequence of n element A, the behavior of the third sequence of m elements B (separated by a space between the elements) . n = 0 and m = 0, the input end.

Export

For each line of output data, the combined sequence, separated by spaces between each data.

Sample input 1

5 5
1 3 5 7 9
2 4 6 8 10
3 4
1 5 9
1 2 5 9
0 0

Sample Output 1

1 2 3 4 5 6 7 8 9 10
1 2 5 9

#include<iostream>
using namespace std;
typedef struct LNode* List;
struct LNode {
    int data;
    List next;
};
void InitList(List &L)
{
    L = new LNode;
    L->next = NULL;
}
void CreatList(List &L,int num)
{
    L = new LNode;
    L->next = NULL;
    List r = L;
    for (int i = 0; i < num; i++)
    {
        List p = new LNode;
        cin >> p->data;
        p->next = NULL;
        r->next = p;
        r = p;
    }
}
List MergeList(List a,List b )
{
    List c;
    List pa, pb, pc;
    pa = a->next;
    pb = b->next;
    c = a;
    pc = c;
    while (pa&&pb)
    {
        if (pa->data < pb->data)
        {
            pc->next = pa;
            pc = pa;
            pa = pa->next;
        }
        else
        {
            if (pa->data > pb->data)
            {
                pc->next = pb;
                pc = pb;
                pb = pb->next;
            }
            else
                if (pa->data == pb->data)
                {
                    pc->next = pa;
                    pc = pa;
                    pa = pa->next;
                    pb = pb->next;
                }
        }
    }
    PC -> the Next = PA PA: pb;? // if not pa, might be a empty 
    the Delete b;
     return c;
}
void Print(List L)
{
    List p = L->next;
    while (p->next)
    {
        cout << p->data << " ";
        p = p->next;
    }
    cout << p->data<<endl;
}
int main ()
{
    int n, m;
    while (cin>>n>>m&&(n != 0 || m != 0))
    {
        List A, B;
        CreatList (A, n);
        CreatList(B, m);
        List C=MergeList(A, B);
        Print(C);
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/h694879357/p/11672332.html