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

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;
}
相关推荐
自信1504130575931 分钟前
初学者小白复盘15之指针(4)
c语言·数据结构·算法
.格子衫.1 小时前
021数据结构之并查集——算法备赛
数据结构·算法
刚入坑的新人编程2 小时前
算法训练.17
开发语言·数据结构·c++·算法
TinpeaV2 小时前
String[ ] 和 List<String> 的区别
数据结构·list
遇见好心情.2 小时前
双向链表的实现
数据结构·链表
软行3 小时前
LeetCode 每日一题 166. 分数到小数
数据结构·c++·算法·leetcode·哈希算法
阿昭L3 小时前
leetcode合并有序链表
leetcode·链表
大数据张老师3 小时前
数据结构——B树及其基本操作
数据结构·b树·前端框架
伟大的车尔尼4 小时前
双指针的概念
数据结构·算法·双指针