比较三张顺序表/链表中的重复元素并删除
最近做的数据结构作业,不BB直接上代码:
一、顺序表
#include <stdio.h>
#include<malloc.h>
#define DATATYPE int
#define MAXSIZE 100
typedef struct
{
DATATYPE data[MAXSIZE];
int len;
}sequenlist;
sequenlist* InitList(){//建立空顺序表
sequenlist *L = (sequenlist*)malloc(sizeof(sequenlist));
L->len = 0;
return L;
}
int Insert(sequenlist *L,DATATYPE x,int i){//将新节点插入顺序表的第i个位置
int j;
if(L->len >= MAXSIZE-1){
printf("FULL");
return 0;
}
else{
for(j = L->len;j>=i;j--)
L->data[j]=L->data[j-1];
L->data[i-1] = x;
L->len++;
return 1;
}
}
void Delete(sequenlist *L,int i){
int j;
if((i<1)||(i>L->len)){
printf("Illegal");
}
else{
for(j=i+1;j<=L->len;j++)
L->data[j-2]=L->data[j-1];
L->len--;
}
}
void Delete_Same(sequenlist *LA,sequenlist *LB,sequenlist *LC){
//删除三个表的重复值
int i,j,k;
for(i=0;i<LA->len;i++){
for(j=0;j<LB->len;j++){
for(k=0;k<LC->len;k++){
if((LA->data[i]==LB->data[j]) && (LA->data[i]==LC->data[k])){
Delete(LA,i+1);
}
}
}
}
}
void print(sequenlist *L){
int i;
for(i=1;i<=L->len;i++){
printf("%d ",L->data[i-1]);
}
printf("\n");
}
int main() {
sequenlist *LA,*LB,*LC;
int i=0,j=0,k=0;
DATATYPE x,y,z;
LA = InitList();
printf("create LA,-1 is over:\n");
scanf("%d",&x);
while(x!=-1){
i++;
if(!Insert(LA,x,i)) break;
scanf("%d",&x);
}
LB = InitList();
printf("create LB,-1 is over:\n");
scanf("%d",&y);
while(y!=-1){
j++;
if(!Insert(LB,y,j)) break;
scanf("%d",&y);
}
LC = InitList();
printf("create LC,-1 is over:\n");
scanf("%d",&z);
while(z!=-1){
k++;
if(!Insert(LC,z,k)) break;
scanf("%d",&z);
}
printf("LA:");
print(LA);
printf("LB:");
print(LB);
printf("LC:");
print(LC);
Delete_Same(LA,LB,LC);
printf("After Delete:");
print(LA);
}
运行截图:
二、链表
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node *next;
}linklist;
linklist* CreateListR(){//尾插法创建链表
linklist *L;
L = (linklist*)malloc(sizeof (linklist));
L->next = NULL;
linklist *r;
r = L;
int x=0;
while (x != -1){
scanf("%d",&x);
linklist *p;
p = (linklist*) malloc(sizeof (linklist));
p->data = x;
r->next = p;
r = p;
}
r->next = NULL;
return L;
}
void print(linklist *L){
linklist *p = L->next;
while(p->next){
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
void Delete(linklist *L,int x){//删除单个元素
linklist *t=L->next;
linklist *b=L;
while(t != NULL){
if(t->data == x){
b->next = t->next;
free(t);
t = b;
}
b=t;
t=t->next;
}
}
void DeleteSame(linklist *LA,linklist *LB,linklist *LC){//在LA中删除三张表中相同元素
for(linklist *j=LB->next;j->next!=NULL;j=j->next){
for(linklist *k=LC->next;k->next!=NULL;k=k->next){
if(j->data == k->data){
Delete(LA,j->data);
}
}
}
}
int main() {
linklist *LA,*LB,*LC;
printf("create LA:");
LA = CreateListR();
printf("create LB:");
LB = CreateListR();
printf("create LC:");
LC = CreateListR();
printf("print LA:");
print(LA);
printf("print LB:");
print(LB);
printf("print LC:");
print(LC);
printf("LA after delete:");
DeleteSame(LA,LB,LC);
print(LA);
return 0;
}
运行截图: