王道2.15

//已知两个链表A和B分别表示两个集合,其元素递增排列。

#include

#include

#include

using namespace std;

typedef struct Lnode{

    int data;

    struct Lnode *next;

}Lnode,*LinkList;

void init_LinkList(LinkList &head){

    int x;

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

    head->next= NULL;

    Lnode *p,*r = head;

    cout<<"请输入数字(-1结束):";

    cin>>x;

    while(x != -1){

        p = (Lnode*)malloc(sizeof(Lnode));

        p->next = r->next;

        p->data = x;

        r->next = p;

        r= p;

        cout<<"请输入数字(-1结束):";

        cin>>x;

       }

   } //编制函数,求A与B的交集,并存放于A链表中。

void create_unity(LinkList &L1,LinkList L2){

    Lnode *p = L1,*p1 = L1->next,*p2= L2->next,*temp;

    while(p1!=NULL&&p2!=NULL){

        if(p1->data>p2->data){

                p2 = p2->next;

        }else if(p1->data < p2->data){

            temp = p1;

            p1 = p1->next;

            p->next = p1;

            free(temp);

         }else{

            p->next = p1;

            p = p1;

            p1 = p1->next;

            p2 = p2->next;

            }

        }

        p->next = NULL;

}

int main(){

    LinkList L1,L2;

    init_LinkList(L1);

    init_LinkList(L2);

    Lnode *p; p = L1->next;

    while(p != NULL){

        cout<data<<" ";

        p = p->next;

      }

    cout<

    p = L2->next;

    while(p != NULL){

        cout<data<<" ";

        p = p->next;

    }

    cout<

    create_unity(L1,L2);

    p = L1->next;

    while(p != NULL){

        cout<data<<" ";

        p = p->next;

    }

}

你可能感兴趣的:(王道2.15)