单向链表
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node,*List;
bool initList(List &l){
l=(Node*)malloc(sizeof(Node));
if(l==NULL){
return false;
}
l->next=NULL;
return true;
}
bool listInsert(List l,int n,int e){
if(n<1){
return false;
}
Node* p=l;
int i=0;
while(p!=NULL&&i<n-1){
p=p->next;
i++;
}
if(p==NULL){
return false;
}
Node* s=(Node*)malloc(sizeof(Node));
s->next=p->next;
p->next=s;
s->data=e;
return true;
}
bool listDelete(List l,int e){
Node* p=l->next;
Node* q=l;
while(p!=NULL&&p->data!=e){
p=p->next;
q=q->next;
}
if(p==NULL){
return false;
}
q->next=p->next;
free(p);
}
int searchByElem(List l,int e){
Node *p=l->next;
int i=1;
while(p!=NULL&&p->data!=e){
p=p->next;
i++;
}
if(p==NULL){
return -1;
}
return i;
}
void clearList(List l){
Node *p=l->next;
Node *q=l;
while(p!=NULL){
q=p;
p=p->next;
free(q);
}
l->next=NULL;
printf("清空集合成功!\n");
}
void getIntersection(List a,List b){
Node *p=a->next;
printf("交集:\n");
while(p!=NULL){
if(searchByElem(b,p->data)!=-1){
printf("%d\n",p->data);
}
p=p->next;
}
}
void getUnion(List a,List b){
printf("并集:\n");
Node *p=a->next;
while(p!=NULL){
printf("%d\n",p->data);
p=p->next;
}
p=b->next;
while(p!=NULL){
if(searchByElem(a,p->data)==-1){
printf("%d\n",p->data);
}
p=p->next;
}
}
void getSubs(List a,List b){
printf("差集:\n");
Node *p=a->next;
while(p!=NULL){
if(searchByElem(b,p->data)==-1){
printf("%d\n",p->data);
}
p=p->next;
}
}
void printList(List l){
Node *p=l->next;
printf("**********\nList:\n");
int i=0;
while(p!=NULL){
printf("data[%d]:%d\n",i++,p->data);
p=p->next;
}
printf("**********\n");
}
int main(){
List l;
initList(l);
printList(l);
listInsert(l,1,10);
listInsert(l,2,20);
listInsert(l,3,30);
listDelete(l,20);
List li;
initList(li);
listInsert(li,1,11);
listInsert(li,1,21);
listInsert(li,1,20);
listInsert(li,1,30);
printList(l);
printList(li);
getIntersection(l,li);
getUnion(l,li);
getSubs(l,li);
return 0;
}