链表必学算法(三):归并法

   日期:2020-05-10     浏览:154    评论:0    
核心提示:必学算法数据结构与算法





typedef struct node {
	Elemtype data;
	struct node* next;
} Lnode;



Lnode* merge1(Linklist& LA, Linklist& LB) {
	// merge two sorted Singly linked lists
	// LA, LB and the return one ( LC ) all have a head node
	// all the linklist are sorted in the same way: increasing or decreasing
	// we assume that all the slists are sorted in an increasing order
	// KEY: insert in the tail

	Lnode* LC = (Lnode*)malloc(sizeof(Lnode));
	LC->next = NULL;
	Lnode* pa = LA->next, * pb = LB->next, * pc = LC;

	while (pa && pb) { 
		if (pa->data < pb->data) {
			pc->next = pa;
			pa = pa->next;
		}
		else {
			pc->next = pb;
			pb = pb->next;
		}
		pc = pc->next;
	}

	if (pa) pc->next = pa;
	if (pb) pc->next = pb;
	return LC;
}



Lnode* merge2(Linklist& LA, Linklist& LB) {
	// merge two sorted Singly linked lists
	// LA, LB and the return one ( LC ) all have a head node
	// all the linklist are sorted not in the same way: 
	// LA and LB are the same, but LC just the other way
	// we assume that LA and LB are sorted in an increasing order
	// KEY: insert in the front

	Lnode* LC = (Lnode*)malloc(sizeof(Lnode));
	LC->next = NULL;
	Lnode* pa = LA->next, * pb = LB->next;

	while (pa && pb) {
		Lnode* temp = NULL;
		if (pa->data < pb->data) {
			temp = pa->next;
			pa->next = LC->next;
			LC->next = pa;
			pa = temp;
		}
		else {
			temp = pb->next;
			pb->next = LC->next;
			LC->next = pb;
			pb = temp;
		}
	}

	if (pa) pc->next = pa;
	if (pb) pc->next = pb;
	return LC;
}
 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
更多>相关资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服