有序表的合并-用链表操作

2021/10/15 23:15:15

本文主要是介绍有序表的合并-用链表操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

/*
	有序表的合并---用链表实现 
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef int ElemType;
typedef struct Lnode{
	ElemType data;
	struct Lnode * next;
}LNode, * LinkList;


void CreateList_R(LinkList * L){
	int len;
	printf("请输入要创建的链表节点个数:");
	scanf("%d", &len);
	*L = (LinkList)malloc(sizeof(LNode) * len);
	int i;
	int val;
	LinkList r;
	r = *L;
	for(i = 0; i < len; i++){
		printf("请输入第%d个节点存入的值:\n", i + 1);
		scanf("%d", &val);
		LinkList s = (LinkList)malloc(sizeof(LNode)); 
		s->data = val;
		s->next = NULL;
		r->next = s;
		r = s;
	}
}

void traverse_list(LinkList L){
	LinkList p = L->next;
	while(p){
		printf("%d ", p->data);
		p = p->next;
	}
}

/*
	有序表合并---用链表实现 
*/
LinkList MergeList_L(LinkList  La, LinkList  Lb){
	LinkList  Lc;
	LinkList pa = La->next;
	LinkList pb = Lb->next;
	Lc = La;
	LinkList pc = La;
	while(pa && pb){
		if(pa->data <= pb->data){
			pc->next = pa;
			pc = pa;
			pa = pa->next;
		}else{
			pc->next = pb;
			pc = pb;
			pb = pb->next;
		}
	}
	pc->next = pa?pa:pb;
	free(Lb);	
	return Lc;
}
int main(){
	LinkList La;
	LinkList Lb;
	LinkList Lc;
	CreateList_R(&La);
	CreateList_R(&Lb); 
	
	Lc = MergeList_L(La, Lb);
	traverse_list(Lc);
	return 0;
} 


这篇关于有序表的合并-用链表操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程