【Python】【力扣】刷题Day1——合并两个有序链表

提示:仅供参考


力扣题目链接:
链接: link

一、合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例1:
在这里插入图片描述
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:

示例2:
输入:l1 = [], l2 = []
输出:[]
示例 3:

示例3:
输入:l1 = [], l2 = [0]
输出:[0]

提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列

二、思路

1.合并两个链表,如果有一个链表是空,直接返回另一个链表即可

2.如果两个链表都不为空

新建一个链表,从list1和list2的头节点开始进行比较,哪个小就将哪个节点插在新建链表的末尾,直至其中一个链表全部插入完成,再将另一个链表剩下的节点全部插入新建链表的末尾,合并即可完成
1.初始化一个节点 list3 = ListNode()
2.定义一个头指针head指向这个节点
3.list1和list2都是指向链表头的指针,当这两个指针都不为空的时候,进入循环:
如果list1的头节点数值较小:
list3的next指针指向list1
list1的next指针指向list1的下一个节点;

if list1.val <= list2.val :
	list3.next = list1
	list1 = list1.next

如果list2的头节点数值较小:
list3的next指针指向list2
list2的next指针指向list2的下一个节点。

else :
	list3.next = list2
    list2 = list2.next

问题:为什么这里用if list1.val > list2.val不行?
因为在如果list1.val <= list2.val,list1就会指向list1的下一个节点,这时list1就可能已经指向一个空节点了,与list2进行比较就会报错。

这样一个节点就插入完毕了,这时list3要向后移动,方便插入下一个节点;而head指针不需要移动,因为需要记录新链表的头节点:list3指向list3的next。
如果list1全部插入完成,那list1就会指向none,这时需要将list2的全部节点插入list3后面;
如果list2全部插入完成,那list2就会指向none,这时需要将list1的全部节点插入list3后面。
以上可以将两个链表升序合并,返回head链表的next是返回新的链表。

问题:为什么这里是返回head.next而不是head?
因为在前面定义的时候,list3是一个初始化的节点,值为0,head是指向这个初始化节点的,所以head的值也为0,head.next才是新链表的第一个节点。

三、代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if list1 == None:
            return list2
        if list2 == None:
            return list1
        list3 = ListNode()
        head = list3
        while list1 != None and list2 !=None:
            if list1.val <= list2.val :
                list3.next = list1
                list1 = list1.next
            else :
                list3.next = list2
                list2 = list2.next
            list3 = list3.next
        if list1 == None:
            list3.next = list2
        elif list2 == None :
            list3.next = list1
        return head.next

四、学习总结

init函数是ListNode类的构造函数,也是初始方法
这个ListNode 类定义了一个单链表节点的基本结构,每个节点包含两个属性:
val:存储节点的值,默认值是0。
next:指向下一个节点的指针,默认值是None,表示当前节点没有下一节点。
通过这个类,可以创建和操作单链表中的节点。例如,可以创建多个节点并将它们链接在一起,形成一个链表。
创建节点:
node1 = ListNode(1)
node2 = ListNode(2)
将两个节点连接起来:
node1.next = node2


### Python LeetCode Practice Problems and Solutions #### Example Problem: Subsets (LeetCode 78) A common problem encountered when practicing algorithms with Python on LeetCode involves generating all possible subsets of a given set of distinct integers. The provided code snippet demonstrates an effective method for solving this issue through backtracking. ```python from typing import List class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: def backtrack(first=0, curr=[]): # If the combination is completed if len(curr) == k: output.append(curr[:]) return for i in range(first, n): # Add nums[i] into the current combination curr.append(nums[i]) # Use next integers to complete the combination backtrack(i + 1, curr) # Backtrack curr.pop() output = [] n = len(nums) for k in range(n + 1): backtrack() return output ``` This implementation uses recursion alongside iteration to explore every potential subset while maintaining efficiency[^3]. When approaching such problems, one should consider multiple approaches ranging from brute-force methods to more optimized ones. For instance, discussing alternative strategies can include mentioning how another approach might offer trade-offs between time and space complexities[^2]. For example, instead of using backtracking, one could also implement iterative logic based on bit manipulation or dynamic programming principles depending upon specific constraints mentioned within each challenge description. In addition to mastering these techniques, participating actively in online communities dedicated to coding challenges like Stack Overflow or Reddit's r/learnprogramming forums provides valuable insights as well as opportunities for collaborative learning experiences where individuals share their knowledge freely under open-source values[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值