【数据结构】-线性表-链表 熟练度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;
}

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...