【链表】merge两个非递减的链表为一个非递减的链表

21 篇文章 0 订阅
14 篇文章 0 订阅
LinkList *MergeList(LinkList *la, LinkList *lb)
{
	LinkList *lc,*pa,*pb,*pc;
	lc = pc = la;
	pa = la->next;
	pb = lb->next;
	
	while(pa != NULL && pb !=NULL)
	{
		if(pa->data <= pb->data)
		{
			pc->next = pa;
			pc = pa;
			pa = pa->next;
		}
		else
		{
			pc->next = pb;
			pc = pb;
			pb = pb->next;
		}
	}
	
	//pa == NULL ? pc->next = pb : pc->next = pa;
	pc->next = pa ? pa : pb;
	
	free(lb);
	
	return lc;
}
可以按照以下步骤实现: 1. 定义两个链表的指针,分别指向两个递减链表的头结点。 2. 定义一个链表的指针,初始值为 NULL。 3. 循环比较两个链表的头结点的值,将较小的值插入到新链表的头部,并将指向该节点的指针后移。 4. 重复步骤 3 直到两个链表中有一个为空。 5. 将剩余的链表连接到新链表的尾部。 6. 返回新链表的头指针。 以下是示例代码: ```c #include <stdio.h> #include <stdlib.h> struct node { int val; struct node* next; }; struct node* merge_lists(struct node* l1, struct node* l2) { struct node* new_head = NULL; struct node** p = &new_head; while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { *p = l1; l1 = l1->next; } else { *p = l2; l2 = l2->next; } p = &((*p)->next); } if (l1 != NULL) { *p = l1; } else { *p = l2; } struct node* prev = NULL; struct node* curr = new_head; while (curr != NULL) { struct node* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } int main() { struct node* l1 = (struct node*)malloc(sizeof(struct node)); struct node* l2 = (struct node*)malloc(sizeof(struct node)); struct node* p1 = l1; struct node* p2 = l2; // 构造两个递减链表 for (int i = 1; i <= 5; i++) { p1->val = i; p1->next = (struct node*)malloc(sizeof(struct node)); p1 = p1->next; p2->val = i + 5; p2->next = (struct node*)malloc(sizeof(struct node)); p2 = p2->next; } p1->next = NULL; p2->next = NULL; struct node* merged_list = merge_lists(l1, l2); // 输出合并后的递减链表 while (merged_list != NULL) { printf("%d ", merged_list->val); merged_list = merged_list->next; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值