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

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 小时前
【数据结构】栈和队列
c语言·数据结构
chao_7894 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
秋说4 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
qqxhb6 小时前
零基础数据结构与算法——第四章:基础算法-排序(中)
数据结构·算法·排序算法·归并·快排·堆排
木叶丸7 小时前
编程开发中,那些你必须掌握的基本概念
前端·数据结构·编程语言
Y1nhl7 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
手握风云-8 小时前
优选算法的链脉之韵:链表专题
数据结构·算法·链表
老虎062710 小时前
数据结构(Java)--位运算
java·开发语言·数据结构
小汉堡编程13 小时前
数据结构——vector数组c++(超详细)
数据结构·c++
雾里看山16 小时前
顺序表VS单链表VS带头双向循环链表
数据结构·链表