设head1和head2分别指向两个带表头结点的升序链表,将两个升序链表合并成一个升序链表并去重复值

#include<stdio.h>
#include<stdlib.h>
#define N 5
#include"toulianbiao.h"//与前文的“lianbiao.h”类似,此处为带表头结点的链表
void Delkeynode(ElemSN *head1,ElemSN *head2)
{
	ElemSN *p,*tail,*h1=NULL,*s;
	while(head1->next&&head2->next){//找出两者最小的 
		if(head1->next->data>head2->next->data){
			p=head2->next;
			head2->next=p->next;
		}
		else{
			p=head1->next;
			head1->next=p->next;
		}
		p->next=NULL;
		if(!h1){
			h1=tail=p;
		}
		else{
			if(p->data!=tail->data){//判断是否为重复值,并挂链 
				tail=tail->next=p; 
			}
			else{
				free(p);
			}
		}
	}
		if(head1->next){//head2先跑完 
			s=head1->next;
			free(head2); 
		}
		else{
			s=head2->next;
		}
		while(s){
			p=s;
			s=s->next;
			p->next=NULL;
			if(p->data!=tail->data){//排除重复值 
				tail=tail->next=p;
			}
			else{//删除重复值 
				free(p);
			}
		}
		head1->next=h1;
} 
int main()
{
	int a[N],i,key,b[N];
	printf("Please input the number of a[N]:");
	for(i=0;i<N;i++){
		scanf("%d",&a[i]);
	}
	printf("\n");
	printf("Please input the number of b[N]:");
	for(i=0;i<N;i++){
		scanf("%d",&b[i]);
	}
	ElemSN *head1=NULL,*head2=NULL;
	//调用createlink函数   创建带表头单向链表 
	head1=Createlink(a);
	head2=Createlink(b);
	//删除关键字值为key的结点 
	Delkeynode(head1,head2);
	free(head2);
	//调用prelink函数  输出 
	Printlink(head1);
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_42727102/article/details/88880658