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;
	}
};


leetcode之路021 Merge Two Sorted Lists

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

LeetCode021 Merge Two Sorted Lists

详细见:leetcode.com/problems/merge-two-sorted-lists Java Solution: github package leetcode; im...
  • zxwtry
  • zxwtry
  • 2017年03月30日 11:21
  • 123

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
  • 3446

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

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

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 made by splici...
  • LZTree
  • LZTree
  • 2017年04月12日 17:01
  • 168

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...
  • buptlrw
  • buptlrw
  • 2016年02月28日 10:09
  • 442

leetCode 21.Merge Two Sorted Lists (合并排序链表) 解题思路和方法

Merge Two Sorted Lists  Merge two sorted linked lists and return it as a new list. The new list sho...

LeetCode - Merge Two Sorted Lists

题注 这题本身不难,但是有很多细节的地方需要考虑。我感觉还是因为自己对于链表本身的操作不熟练,导致好几次上传都没有被accept。还是需要继续练习啊! 题目 Merge two sorted lin...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 021 —— Merge Two Sorted Lists
举报原因:
原因补充:

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