数据结构练习:求两个集合的并集——用数组创建链表(尾插法建表)

#include<stdio.h>
#include<stdlib.h>
#define len sizeof(LNode)
typedef int ElemType;

typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode,*Link;

void Create(Link &L,int a[],int n){//用数组创建链表,a[]是数组,n是数组元素个数
    Link s,r;
    int i;
    L = (Link)malloc(len);
    r = L;                        //采用尾插法创建链表
    for(i = 0; i < n; i++)
    {
        s = (Link)malloc(len);   //建立新节点
        s->data = a[i];          //将数组元素值赋给结点s
        r->next = s;             //s结点插入到链尾
        r = s;
    }
    r->next = NULL;
}


int LocateElem(Link L,int x)//判断元素是否相等
{
    int flag = 1;
    Link p = L->next;
    while(p != NULL)
    {
        if(p->data == x)//如果元素相等,令flag = 0 
        {
            flag = 0;
            p = p->next;//循环条件
        }
        else//如果元素不相等,也要循环遍历整个链表
            p = p->next;
    }
    return flag;
}
/*LocateElem结果:flag = 0,元素相等,flag = 1,元素不相等
                if(LocateElem()) 即: if(LocateElem() == 1)
                if(!LocateElem()) 即: if(LocateElem() == 0)
*/

int ListLength(Link L)//求链表长度
{
    int n = 0;
    Link p = L;
    while(p->next != NULL)
    {
        n++;
        p = p->next;
    }
    return n;
}

void Union(Link La, Link Lb)
{
    int n;
    Link p,q,s;
    n = ListLength(La);
    p = La->next;
    q = Lb;
    while(p->next != NULL)
    {
        p = p->next;//当p指向La的尾节点结束循环,方便Lb中元素尾插法插入到La中
    }
    while(q && q->next)
    {
        if(LocateElem(La,q->next->data))//元素不相等
        {
            s = q->next;
            q->next = s->next;//q向后移动一个位置
            s->next = NULL;//将s插入到表尾做准备
            p->next = s;   //将s插入到表尾
            p = s;         //p指向为节点
        }
        else
            q = q->next;
    }
}


void Print(Link L)//遍历输出链表
{
    Link p = L->next;
    while(p != NULL)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
}

int main()
{
    int i,j,m,n;
    int a[20];
    int b[20];
    Link A,B,C,p,q;
    scanf("%d%d",&m,&n);
    for(i = 0; i < m; i++)
        scanf("%d",&a[i]);
    for(j = 0; j < n; j++)
        scanf("%d",&b[j]);
    Create(A,a,m);
    Create(B,b,n);
    Union(A,B);
    printf("%d\n", ListLength(A));
    Print(A);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Leiqian5757/article/details/85316723