马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 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 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
The number of nodes in both lists is in the range [0, 50].
-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[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
https://leetcode.com/problems/me ... on-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 tempclass 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 recursionclass 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
|