【朱迪的LeetCode刷题笔记】】21. Merge Two Sorted Lists #Easy #Python
本帖最后由 Judie 于 2023-5-29 21:06 编辑You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = , list2 =
Output:
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 =
Output:
Constraints:
The number of nodes in both lists is in the range .
-100 <= Node.val <= 100
Both list1 and list2 are sorted in non-decreasing order.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional
:type list2: Optional
:rtype: Optional
"""
https://leetcode.com/problems/merge-two-sorted-lists/solutions/759870/python3-solution-with-a-detailed-explanation-dummy-explained/
Solution 1
by using variables dummy and temp
dummy is pointing to the start i.e. dummy makes sure we don;t loose the head of the thread (result list)
temp makes the linkes from node to node i.e we are traversing using temp
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = temp = ListNode(0)
while l1 != None and l2 != None: #1
if l1.val < l2.val: #2
temp.next = l1 #3
l1 = l1.next #4
else:
temp.next = l2
l2 = l2.next
temp = temp.next
temp.next = l1 or l2#5
return dummy.next #6
Solution 2
by doing recursion
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 or not l2:
return l1 or l2
if l1.val <= l2.val: #1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else: #2
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
Judy
{:10_275:} 我觉得我也得慢慢习惯看英文,有时候中文的机翻有点看不懂什么意思 yinda_peng 发表于 2023-5-27 00:33
我觉得我也得慢慢习惯看英文,有时候中文的机翻有点看不懂什么意思
嗯嗯!你生活在哪啊 我是生活在北美 yinda_peng 发表于 2023-5-27 00:33
别说了别说了 这题我没写出来 看的别人的solution
更离谱的是 我翻我记录 这题我一两年前拿c写出来过 Judie 发表于 2023-5-27 22:46
嗯嗯!你生活在哪啊 我是生活在北美
在湖南呐,小城市出来的,衡阳人 yinda_peng 发表于 2023-5-28 00:09
在湖南呐,小城市出来的,衡阳人
那你英文真不错!
页:
[1]