LeedCode_合并两个有序链表

LeedCode_合并两个有序链表

题目说明

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
分析:基本的归并套路

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
	{
		if (l1 == NULL)
		{
			return l2;
		}
		if (l2 == NULL)
		{
			return l1;
		}
		ListNode* q = l1;
		ListNode* p = l2;
		ListNode* res;
		ListNode* t;
		if (p->val > q->val)
		{
			t = q->next;
			res = q;
			res->next = NULL;
			q = t;
		}
		else
		{
			t = p->next;
			res = p;
			res->next = NULL;
			p = t;
		}
		ListNode* pre = res;
		while (q!=NULL&&p!=NULL)
		{
			if (p->val > q->val)
			{
				t = q->next;
				q->next = pre->next;
				pre->next = q;
				pre = q;
				q = t;
			}
			else
			{
				t = p->next;
				p->next = pre->next;
				pre->next = p;
				pre = p;
				p = t;
			}
		}
		if (q != NULL)
		{
			pre->next = q;
		}
		if (p != NULL)
		{
			pre->next = p;
		}
		return res;
	}
发布了63 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/luncy_yuan/article/details/104074667