两个升序链表的合并算法

数据结构线性表的运用把两个升序链表合并成一个且不借助第三个链表

代码如下:

#include
#include

struct Data{
	int index;
	struct Data * next;
};

struct Data * create(){ //创建升序链表 
	printf("请输入一个升序列表以0结束\n");
	struct Data *p1,*p2,*head;
	head = p1 = p2 = (struct Data *)malloc(sizeof(struct Data));
	scanf("%d",&p1->index);
	while(p1->index){
		p2->next=p1;
		p2=p1;
		p1=(struct Data *)malloc(sizeof(struct Data));
		scanf("%d",&p1->index);
	}
	p2->next=NULL;
	printf("建立成功!\n");
	return head; 
}

void print(struct Data *head){//打印链表 
	while(head){
		printf("%d\t",head->index);
		head=head->next; 
	}
	printf("\n");
}

struct Data * combineList(struct Data *head1,struct Data *head2){
	struct Data * head3,* head4;
	head4=head3=head1->index<=head2->index?head1:head2;//对链表的预处理确定头指针应该是以head1开始还是以head2开始 
	if(head1->index<=head2->index){
		head1=head1->next;//防止使head3->next==head3构成死循环 
	}else{
		head2=head2->next;
	}
	while(head1&&head2){//合并链表 
		if(head1->index<=head2->index){//比较当前两个结构体的值的大小 
			head3->next = head1;//上一个值与较小的当前值链接 
			head3 = head3->next;//指针后移 
			head1 = head1->next;//指针后移 
		}else{
			head3->next = head2;//上一个值与较小的当前值链接 
			head3 = head3->next;//指针后移 
			head2 = head2->next;//指针后移 
		}
	}
	head3->next = head3->next==head1?head2:head1;
	return head4;
}
int main(){
	struct Data *head1,*head2,*head3;
	head1=create();
	print(head1);
	head2=create();
	print(head2);
	head3=combineList(head1,head2);
	printf("合并之后:\n");
	print(head3);
}

 

你可能感兴趣的:(算法)