单链表求集合

来源:互联网 发布:excel两个表格数据相同 编辑:程序博客网 时间:2024/05/29 13:21


#include<stdio.h>#include<malloc.h>typedef struct list{int num;struct list *next;}*LIST,listint;LIST Creat(char n){LIST head,p1,p2;head=p1=(LIST)malloc(sizeof(listint));printf("请输入%c单链表集合(以0未结束符):",n);scanf("%d",&p1->num);if(p1->num==0)return head;p1->next=NULL;while(1){p2=(LIST)malloc(sizeof(listint));scanf("%d",&p2->num);p2->next=NULL;if(p2->num==0)return head;p1->next=p2;p1=p2;}}LIST range(LIST head){LIST p1,p2,p3,p4;p1=p2=p3=head;char n=1;p4=(LIST)malloc(sizeof(listint));p4->next=NULL;while(p1!=NULL){while(p2!=NULL){if(p2->next!=NULL&&p1->next!=NULL&&n==1){p3=p2;p2=p2->next;}n=1;if(p1->num==p2->num){p3->next=p2->next;p2=p2->next;n=0;}else if(p2->next==NULL)p2=NULL;}p3=p2=p1=p1->next;}p1=head;p2=p1->next;while(p1->next!=NULL){if(p1->num>p2->num){p4->num=p1->num;p1->num=p2->num;p2->num=p4->num;}if(p2->next==NULL){p1=p1->next;p2=p1->next;}else if(p2->next!=NULL)p2=p2->next;}return head;}LIST And(LIST h1,LIST h2){int n=0;LIST p1,p2,p3,p4,h3;p1=h1;p2=h2;    h3=p3=(LIST)malloc(sizeof(listint));p3->num=-1;p3->next=NULL;while(p1!=NULL&&p2!=NULL){while(p1->num>p2->num){if(p2->next!=NULL)p2=p2->next;elsereturn h3;}while(p1->num<p2->num){if(p1->next!=NULL)p1=p1->next;elsereturn h3;}if(p1->num==p2->num){n++;if(n!=1){p3->next=p4;p3=p3->next;p4->num=p1->num;}elsep3->num=p1->num;p4=(LIST)malloc(sizeof(listint));p4->next=NULL;p2=p2->next;}}return h3;}void print(LIST head){LIST L;L = head;while(L!=NULL){if(L->num!=-1){printf("%d  ",L->num);L = L->next;}else{printf("没有交集!\n");L=NULL;}}}void main(){LIST h1,h2,h3;while(1){h1=Creat('A');h2=Creat('B');h1=range(h1);h2=range(h2);print(h1);printf("\n");print(h2);h3=And(h1,h2);printf("\n");printf("得到交集为:\n");print(h3);printf("\n");}}


运行结果:

请输入A单链表集合(以0未结束符):5 4 3 2 1 0

请输入B单链表集合(以0未结束符):2 2 2 5 4 2 3 2 3 2 3 9 8 7 6 5 5 4 4 7 7 6 5 0

1 2 3 4 5

2 3 4 5 6 7 8 9

得到交集为:

2 3 4 5 

请输入A单链表集合:

作者:陈福林(fulinux)

20111227

本文由麻辣烫培训网转载发布,转载请注明,谢谢
原创粉丝点击