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

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 小时前
四数相加贰——哈希表
数据结构·python·算法·leetcode·散列表
仰泳的熊猫1 小时前
1148 Werewolf - Simple Version
数据结构·c++·算法·pat考试
不穿格子的程序员2 小时前
从零开始学算法——链表篇3:合并两个有序链表 + 两数相加
数据结构·算法·链表·dummy
子一!!2 小时前
数据结构==LRU Cache ==
数据结构
hweiyu002 小时前
数据结构:邻接矩阵
数据结构
Fine姐3 小时前
数据结构01——栈
数据结构
hweiyu003 小时前
数据结构:有向无环图
数据结构
liu****3 小时前
10.排序
c语言·开发语言·数据结构·c++·算法·排序算法
利刃大大4 小时前
【JavaSE】十一、Stack && Queue && Deque && PriorityQueue && Map && Set
java·数据结构·优先级队列··哈希表·队列·集合类
fufu03114 小时前
Linux环境下的C语言编程(三十九)
c语言·数据结构·算法·链表