链表A和B的有序合并,合并过程不产生新的节点,合并后B消失

/*有序链表的合并,合并过程不产生新的节点,如A和B合并,合并和B在A中,B消失*/

#include <iostream>

using namespace std;

typedef struct Node 

{

    int element;

    Node *pNext;

}Node,*LinkList;

void InitList(LinkList& head)

{

    head=(LinkList)malloc(sizeof(Node));

    head->pNext=NULL;

}

int ListLength(LinkList head)

{

    int length=-1;

    LinkList p=head;

    while (p!=NULL)

    {

        length++;

        p=p->pNext;

    }

    return length;

    

}

void InsertList(LinkList& head,int element){

    int length=ListLength(head);

    if(length==-1)

        return;

    LinkList q=head;

    LinkList p=head->pNext;

    while (p)

    {

        if (element<p->element)

        {

            break;

        }

        q=p;

        p=p->pNext;

    }

    LinkList temp=(LinkList)malloc(sizeof(Node));

    temp->element=element;

    q->pNext=temp;

    temp->pNext=p;    

}



void PrintList(LinkList head)

{

    if (head==NULL)

    {

        return;

    }

    LinkList p=head->pNext;

    while (p)

    {

        cout<<p->element<<endl;

        p=p->pNext;

    }

}

void DestroyList(LinkList& head)

{

    if(head==NULL)

        return;

    LinkList q=head;

    LinkList p=head->pNext;

    while (p)

    {

        free(q);

        q=p;

        p=p->pNext;

    }

    free(q);

    head=NULL;

}

void InsertList(LinkList& headA,LinkList linklist)

{

    if (headA==NULL)

        return;

    LinkList q=headA;

    LinkList p=q->pNext;

    while (p)

    {

        if (linklist->element<p->element)

        {

            break;

        }

        q=p;

        p=p->pNext;

    }

    q->pNext=linklist;

    linklist->pNext=p;

}

void UnionAB(LinkList &headA,LinkList &headB)

{

    if (ListLength(headB)<1)

        return;

    LinkList q=headB;

    LinkList p=headB->pNext;

    free(headB);

    headB=NULL;

    while (p)

    {

        q=p->pNext;

        InsertList(headA,p);

        p=q;

    }

}

void main()

{

    LinkList headA;

    InitList(headA);

    InsertList(headA,1);

    InsertList(headA,8);

    InsertList(headA,5);

    InsertList(headA,10);

    PrintList(headA);



    LinkList headB;

    InitList(headB);

    InsertList(headB,15);

    InsertList(headB,2);

    InsertList(headB,7);

    InsertList(headB,12);

    PrintList(headB);

    UnionAB(headA,headB);

    PrintList(headA);

    DestroyList(headA);

    DestroyList(headB);



}

你可能感兴趣的:(链表)