链表并集与归并
测试用例:
a[] = {2, 5, 8, 11};
b[] = {2, 6, 8, 9, 11, 15, 20};
输出结果为两个链表LA与LC,其中LA表示a[]
与b[]
的并集,LC表示a[]
与b[]
的归并于排序。
#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define MAXLISTSIZE 20
#define MAXLISTNUMBER 20
struct Student{
int data;
struct Student *next;
};
typedef struct Student List;
List *La,*Lb ,*Lc,*head1 = NULL, *head2 = NULL;
List *CreateList(int temp[],int n);
void Union(List* La, List* Lb);
int IsEqual(int a, int b);
List* UnionND(List* Lc, List* Lb);
void BucketSort(List* L);
void Output(struct Student *p);
int main(){
int temp_a[] = {3,5,8,11};
int temp_b[] = {2,6,8,9,11,15,20};
Lc = La = CreateList(temp_a, sizeof(temp_a)/sizeof(int));
Lb = CreateList(temp_b, sizeof(temp_b)/sizeof(int));
//Output(La);
//Output(Lb);
Union(La, Lb);
Lb = CreateList(temp_b, sizeof(temp_b)/sizeof(int));
Lc = UnionND(Lc, Lb);
//Output(Lc);
BucketSort(Lc);
return 0;
}
List *CreateList(int temp[],int n){
List *head;//指向头结点指针
List *p,*pre;
int i;
head=(List *)malloc(sizeof(List));//为头节点分配内存空间
head->next=NULL;//将头结点的指针域清空
pre=head;//先将头结点首地址赋给中间变量pre
pre->data = temp[0];
for(i=1;i<n;i++){//通过for循环不断加入新的结点
p=(List *)malloc(sizeof(List));//为要插入的节点分配
p->data = temp[i];
pre->next=p;//将p指向新结点插入链表也就是头结点指针域指向
pre=p;//这个起着指向下一个结点的作用
}
p->next=NULL;//最后将最后一个结点的指针域清空了
return head;//返回这个链表的首地址
}
void Union(List* La, List* Lb){
int flag = 0;
List *temp,*cal;
for(temp = Lb; temp->next!=NULL;temp=temp->next);
List *p1, *p2;
p1 = (List*)malloc(sizeof(List));
p2 = (List*)malloc(sizeof(List));
p1 = La;
p2 = Lb;
int i=1;
while(p1){
while(p2){
if(IsEqual(p1->data, p2->data)){
flag = 1;
break;
}
//printf("%d\t",i++);
//printf("%d,%d\n",p2->data,p1->data);
p2 = p2->next;
}
//printf("\nflag=%d\n",flag);
if(!flag){
//printf("error1\n");
cal = (List*)malloc(sizeof(List));
cal->data = p1->data;
temp->next = cal;
temp = cal;
temp->next = NULL;
//printf("error2\n");
}
p2 = Lb;
flag = 0;
p1 = p1->next;
}
printf("并集:LA = (");
for(temp = Lb; temp!=NULL;temp=temp->next)
printf("%d ",temp->data);
printf(")");
printf("\n");
}
int IsEqual(int a, int b){
if(a == b)return 1;
else return 0;
}
List* UnionND(List* Lc, List* Lb){
List *head;
head = Lc;
for(; Lc->next != NULL; Lc = Lc->next);
Lc->next = Lb;
return head;
}
void BucketSort(List* L){
int Bucket[MAXLISTNUMBER+1];
for(int i = 0; i < MAXLISTNUMBER+1; i++)
Bucket[i] = 0;
for(; L !=NULL; L = L->next)
Bucket[L->data]++;
printf("归并后排序:LC = (");
for(int k = 0; k < MAXLISTNUMBER+1; k++)
for(; Bucket[k] > 0; Bucket[k]--)
printf("%d ",k);
printf(")");
}
void Output(struct Student *p)
{
//从头指针一直输出至NULL
struct Student *temp;
for(temp=p;temp!=NULL;temp=temp->next)
{
printf("成绩:%d\n",temp->data);
}
}
实验结果如图