[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List
Posted johnsonxiong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List相关的知识,希望对你有一定的参考价值。
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
这个题目思路就是用dummy node,然后依次判断是l1 小还是l2小,最后当一方是None的时候将另一方加在总list的最后即可。
Code
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1, l2): dummy = ListNode(0) head = dummy while l1 and l2: if l1.val <= l2.val: head.next = l1 l1 = l1.next else: head.next = l2 l2 = l2.next head = head.next head.next = l1 if l1 else l2 return dummy.next
以上是关于[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode---21. Merge Two Sorted Lists
Leetcode 21. Merge Two Sorted Lists
LeetCode 21. Merge Two Sorted Lists
LeetCode算法-21Merge Two Sorted Lists