leetcode 021 —— Merge Two Sorted Lists

原创 2015年07月09日 19:51:57

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.


思路:类似归并排序,双指针扫描链表,值小的,就往新链表后面放,最后补齐多余的链表

class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
		ListNode pre(0);
		ListNode *p = ⪯
		while (l1&&l2){ //有一个为0 就出局
			if (l1->val > l2->val){
				p->next = l2;
				p = l2;
				l2 = l2->next;
			}
			else{
				p->next = l1;
				p = l1;
				l1 = l1->next;
			}
		}
		if (l1) p->next = l1;
		if (l2) p->next = l2;
		return (&pre)->next;
	}
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode021 Merge Two Sorted Lists

详细见:leetcode.com/problems/merge-two-sorted-lists Java Solution: github package leetcode; im...

LeetCode 021 Merge Two Sorted Lists

题: https://leetcode.com/problems/merge-two-sorted-lists/ Merge two sorted linked lists and retur...

[LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)

[LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
  • hcbbt
  • hcbbt
  • 2015-03-04 20:11
  • 3208

leetcode之路021 Merge Two Sorted Lists

题目大意:合并两个有序的链表为一个新链表,新链表必须是原来两个链表元素的组成。即不能新建一个链表,找到两个链表中的小值,新建一个节点对其赋值为此值。也就是说,不能有新建节点的操作(准确点说是能新建,但...

LeetCode OJ——Merge Two Sorted Lists

题目: Merge two sorted linked lists and return it as a new list. The new list should be made by splic...

Leetcode刷题记——21. Merge Two Sorted Lists(合并两有序链表)

一、题目叙述: Merge two sorted linked lists and return it as a new list. The new list should be...

LeetCode算法题——21. Merge Two Sorted Lists

题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splici...

leetcode第21题——*Merge Two Sorted Lists

题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splicin...

LeetCode笔记:21. Merge Two Sorted Lists

合并两个有序链表

[LeetCode] Merge Two Sorted Lists 解题报告

[题目] Merge two sorted linked lists and return it as a new list. The new list should be made by spli...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)