链表题目总结(Easy)

Leetcode:链表题目总结1.翻转一个链表(题号:206)1.尽量处理当前节点的下一个节点而不是当前节点。2.建立虚拟节点作为头节点,解决链表的边界问题。题目:解题代码:class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = nextclass Solution: def reverseList(self, head: ListN
摘要由CSDN通过智能技术生成

Leetcode:链表题目整理

1.尽量处理当前节点的下一个节点而不是当前节点。
2.建立虚拟节点作为头节点,解决链表的边界问题。

1.翻转一个链表(题号:206)

题目:在这里插入图片描述
解题代码:

class ListNode:
    	 def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre=None
        curr=head
        while curr:
            temp=curr.next
            curr.next=pre
            pre=curr#存储当前节点,以作为下一个节点的前节点
            curr=temp
        return pre

思路或技巧:1.将指针的下一个节点存储在临时变量。
           2.pre初始化为None

2.合并两个链表(题号:21)

题目:
在这里插入图片描述
题解:

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        L=d=ListNode(0)
        while l1 and l2:
            if l1.val<=l2.val:
                L.next=l1
                l1=l1.next
            else:
                L.next=l2
                l2=l2.next
            L=L.next
        L.next=l1 or l2
        return d.next

思路:1.创建空节点,作为一个新的链表开端。
           2.迭代遍历两个链表并考虑极端情况

3.删除链表重复元素(题号:83)

题目:
在这里插入图片描述

题解:

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        curr=head
        while curr and curr.next:
        	if curr.val==curr.next.val:
        		curr.next=curr.next.next
        	curr=curr.next
        return head

4.相交链表(题号:160)

在这里插入图片描述
题解:

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    	curr1=l1
    	curr2=l2
    	while curr1!=urr2:
    		curr1=curr1.next if curr1 else l2
    		curr2=curr2.next if curr2 else l1
    	return curr1       

思路:双指针不断循环,找到重合的点并返回

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值