将两个有序链表合并成一个有序链表

cs 复制代码
typedef struct LNode
{
	int val;
	struct LNode* next;
}ListNode;
ListNode* createNode(int val)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("error");
		exit(1);
	}
	newnode->val = val;
	newnode->next = NULL;
	return newnode;
}
ListNode* create_LNode(ListNode* head, int val)
{
	if (head == NULL)
	{
		ListNode* newnode = createNode(val);
		head = newnode;
	}
	else
	{
		ListNode* newnode = createNode(val);
		ListNode* pcur = head;
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = newnode;
	}
	return head;
}
ListNode* create_LA_LBnode(int LA[],int length)
{
	ListNode* head = NULL;
	int i;
	for (i = 0; i < length; i++)
	{
		head = create_LNode(head, LA[i]);
	}
	return head;
}
ListNode* TWO_TO_ONE(ListNode* l1,ListNode*l2)
{
	ListNode temp;
	ListNode* pcur = &temp;
	pcur->next = NULL;
	while (l1 && l2)
	{
		if (l1->val <= l2->val)
		{
			pcur->next = l1;
			l1 = l1->next;
		}
		else
		{
			pcur->next = l2;
			l2 = l2->next;
		}
		pcur = pcur->next;
	}
	pcur->next = l1 ? l1 : l2;
	return temp.next;
}
void printNode(ListNode* head)
{
	ListNode* pcur = head;
	while (pcur)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
int main()
{
	int LA[] = { 3,5,9,11 };
	int LB[] = { 2,4,6,8,10,12 };
	ListNode* ListA = create_LA_LBnode(LA, sizeof(LA) / sizeof(LA[0]));
	ListNode* ListB = create_LA_LBnode(LB, sizeof(LB) / sizeof(LB[0]));
	printNode(ListA);
	printNode(ListB);
	ListNode*LA_LB =  TWO_TO_ONE(ListA, ListB);
	printNode(LA_LB);
	return 0;
}
相关推荐
想要成为糕糕手1 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
tyung3 小时前
Go 手写 Wait-Free SPSC 无界队列:无 CAS、无锁、泛型节点池
数据结构·后端·go
Chen_harmony3 小时前
一、数据结构概念和复杂度计算
数据结构
小欣加油4 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
fie88896 小时前
LBP + HOG 特征检测与识别 MATLAB 实现
数据结构·算法·matlab
退休倒计时7 小时前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript
AbandonForce7 小时前
滑动窗口:定长滑动窗口与不定长滑动窗口
数据结构·c++·算法
炸薯条!7 小时前
二叉树的链式表示(2)
java·数据结构·算法
YHHLAI8 小时前
JavaScript 数据结构精讲:数组底层与实战避坑
开发语言·javascript·数据结构
Coder-magician8 小时前
《代码随想录》刷题打卡day12:二叉树part02
数据结构·c++·算法