线性表的单链表存储表示LaLb求并集

来源:互联网 发布:一类致癌物 知乎 编辑:程序博客网 时间:2024/05/14 01:16
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;


//线性表的单链表存储表示


#define ElemType int


typedef struct Lnode
{
    ElemType data;
    struct Lnode *next;
}Lnode, *Linklist;


void creat(Linklist &L, ElemType A[], int n)
{
    //已知一维数组A[n]中存有线性表的数据元素,逆序创建单链线性表
    L = NULL;
    for(int i = n-1; i >= 0; --i)
    {
        Lnode *s = new Lnode;
        s->data = A[i];
        s->next = L;
        L = s;
    }
}


void InvertLinklist(Linklist &L)
{
    //逆置头指针L所指链表
    Lnode *p = L, *s;
    L = NULL;
    while(p)
    {
        s = p;
        p = p->next;
        s->next = L;
        L = s;
    }
}


int Listlength(Linklist L)
{
    //求L所指离岸边的长度
    Lnode *p = L;
    ElemType k = 0;
    while(p)
    {
        k++;
        p = p->next;
    }
    return k;
}


Lnode *searchE(Linklist L, ElemType e)
{
    //在L中查找第一个和e相等的值,若存在则返回
    Lnode *p = L;
    while(p && p->data != e)
        p = p->next;
    return p;
}


void Insert(Linklist &L, Lnode *p, Lnode *e)
{
    //讲s结点插入到p结点之前
    Lnode *s, *q;
    if(p == L)
    {
        s->next = L;
        L = s;
    }
    else
    {
        q = L;
        while(q->next != p)
            q = q->next;
        q->next = s;
        s->next = p;
    }
}


void show(Linklist &La)
{
    while(La)
    {
        cout<<La->data<<" ";
        La = La->next;
    }
    cout<<endl;
}
void Listdelete(Linklist &L, Lnode *p, ElemType &e)
{
    //删除p结点并返回e
    Lnode *q;
    if(p == L)
    {
        L = p->next;
    }
    else
    {
        q = L;
        while(q->next != p)
            q = q->next;
        q->next = p->next;
    }
    e = p->data;
    delete p;
}


void unionL(Linklist &La, Linklist &Lb)
{
    //将Lb链表中所有在La链表中不存在的结点插入到La链表中
    Lnode *s, *p, *pre;
    if(!La)
        La = Lb;
    else
    {
        while(Lb)
        {
            s = Lb;
            Lb = Lb->next;
            p = La;
            while(p && p->data != s->data)
            {
                pre = p;
                p = p->next;
            }
            if(p)
                delete s;
            else
            {
                pre->next = s;
                s->next = NULL;
            }
        }
    }
    show(La);
}


int main()
{
    Lnode *La, *Lb;
    int A[1000], B[1000], n1 = 0, n2 = 0;
    cout<<"input the size of the Linklist 1:";
    cin>>n1;
    cout<<"input the size of the Linklist 2:";
    cin>>n2;
    cout<<"input the number of Linklist 1:";
    for(int i = 0; i < n1; i++)
    {
        cin>>A[i];
    }
    creat(La, A, n1);
    cout<<"input the number of Linklist 2:";
    for(int i = 0; i < n2; i++)
    {
        cin>>B[i];
    }
    creat(Lb, B, n2);
    cout<<"union La and Lb:";
    unionL(La, Lb);
    return 0;
}
0 0
原创粉丝点击