【数据结构】-线性表-链表 熟练度max=7(链表差集)
发布时间:2020-12-15 05:55:23 所属栏目:安全 来源:网络整理
导读:求差集 输入 A集合:1 2 3 4 5 B集合:4 5 6 7 8 9 10 11 输出 A-B :1 2 3 #includestdio.h#includestdlib.htypedef struct LNode{ int data; struct LNode *next;}LNode; void saveListnext(LNode *L, int x[], int n) //尾插 { L = (LNode *)malloc (size
求差集输入A集合:1 2 3 4 5 输出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;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |