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

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;
}
相关推荐
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245035 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA5 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg15 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA5 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX5 天前
020-C++之unordered容器
数据结构·c++
岛雨QA5 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas5 天前
初识基本排序
java·数据结构·学习方法·排序