代码随想录;Day4

文章目录

  • 1.两两交换链表中节点 力扣:24

  • 2.删除链表中倒数第n个节点 力扣:19

  • 3.链表相交 面试题

  • 4.环形链表II 力扣142

总结



前言

每日刷题,从己做起。

一、两两交换链表中节点

学会画图解题,弄懂实现交换的必备:添加虚拟头结点步骤。

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        res = ListNode(next = head)
        pre = res

        #必须有pre的下一个和下下个才能交换
        while pre.next and pre.next.next:
            cur = pre.next
            post = pre.next.next

            #pre, cur, post对应最左,中间的,最右边的节点
            cur.next = post.next #1位置与3位置传递,
            post.next = cur #2位置与1位置传递,
            pre.next = post #pre位置与2位置传递,

            pre = pre.next.next #更新pre位置
        return res.next

 

二、删除链表中倒数第n个节点

代码如下(示例):

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        head_pre = ListNode()
        head_pre.next = head

        slow, fast = head_pre, head_pre
        while(n>=0):                #移动fast走n步
            fast = fast.next
            n -= 1
        while(fast!=None):          #fast走到尽头即可更新此时二者位置
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next  #删除操作
        return head_pre.next        #不写成head的原因是head可能被删除

三、链表相交

代码如下(示例):

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        lenA, lenB = 0, 0
        cur = headA
        while cur: #求链表A的长度
            cur = cur.next
            lenA += 1
        cur = headB
        while cur: #求链表B的长度
            cur = cur.next
            lenB += 1
        curA, curB = headA, headB
        if lenA > lenB: #使curB为最长链表头,lenB为其长度
            curA, curB = curB, curA
            lenA, lenB = lenB, lenA
        for _ in range (lenB - lenA):
            curB = curB.next
        while curA: #遍历A和B,相同及返回
            if curA == curB:
                return curA
            else:
                curA = curA.next
                curB = curB.next
        return None

四、环形链表II

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
            #如果相遇
            if slow == fast:
                p = head
                q = slow
                while p != q:
                    p = p.next
                    q = q.next
                return p
        return None

总结

学会运用画图分析方法,认真理解代码,定时回顾已学内容。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值