【数据结构】-线性表-链表 熟练度max=7(链表差集)

前端之家收集整理的这篇文章主要介绍了【数据结构】-线性表-链表 熟练度max=7(链表差集)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

求差集

输入

A集合:1 2 3 4 5
B集合:4 5 6 7 8 9 10 11

输出

A-B :1 2 3

#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode;
void saveListnext(LNode *&L,int x[],int n)//尾插
{
    L = (LNode *)malloc (sizeof(LNode));
    L->next=NULL;

    LNode *q;
    q=L;
    LNode *s;
    for(int i=0;i<n;i++)
    {
        s=(LNode *)malloc(sizeof(LNode));
        s->data = x[i];

        q->next=s;
        q=q->next;
    }
    q->next=NULL;
}
void printList(LNode *L)
{
    LNode *q;
    q=L->next;
    int i=0;
    while(q!=NULL)
    {
        if(i++)
            putchar(' ');
        printf("%d",q->data);
        q=q->next;
    }
    printf("\n");
}
void difference(LNode *L,LNode *B)
{
    LNode *q,*b;
    q=L->next;
    b=B->next;

    LNode *pre;//要删出节点前面那一个节点
    pre=L;

    LNode *s;
    while(q!=NULL&&b!=NULL)//必须都不为空
    {
        if(q->data<b->data)
        {
            pre=q;//这一句至关重要,影响到后面删除操作
            q=q->next;
        }
        else if(q->data>b->data)
        {
            b=b->next;
        }
        else
        {
            pre->next=q->next;
            s=q;
            q=q->next;
            free(s);
        }
    }
}
int main (void)
{
    LNode *L,*B;
    int x1[5]={1,2,3,4,5};
    int x2[8]={4,5,6,7,8,9,10,11};
    saveListnext(L,x1,5);
    saveListnext(B,x2,8);
    printList(L);
    printList(B);
    difference(L,B);
    printList(L);
    return 0;
}
原文链接:https://www.f2er.com/datastructure/382350.html

猜你在找的数据结构相关文章