算法训练营Day4(链表)

24. 两两交换链表中的节点 

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

需思考的地方:两个临时指针,while的判断条件(and),cur.next 和 cur.next.next的顺序,最后cur=?

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dumy=ListNode(0)
        dumy.next=head
        cur=dumy
        while cur.next and cur.next.next:
            t=cur.next
            t1=cur.next.next.next
            cur.next=cur.next.next
            cur.next.next=t
            t.next=t1
            cur=cur.next.next

        return dumy.next

力扣19 删除链表的倒数第N个节点力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

注意:设置dumy的好处:不需要判断是否为空指针,可以采用统一的方式进行操作

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dumy=ListNode(0)
        dumy.next=head
        fast=dumy
        slow=dumy
        n=n+1
        while n>0:
            fast=fast.next
            n-=1
        while fast:
            fast=fast.next
            slow=slow.next
        slow.next=slow.next.next
        return dumy.next

没有使用双指针 

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dumy=ListNode(0)
        dumy.next=head
        cur=dumy
        pre=dumy
        l=0
        while pre.next:
            pre=pre.next
            l+=1
        s=l-n
        while s> 0:
            cur=cur.next
            s-=1
        cur.next=cur.next.next
        return dumy.next

力扣 面试题02,07  链表相交

注意:if none就会中断 ,判断headA和headB是否为空指针

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None
        A, B = headA, headB
        while A != B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A

力扣142  环形链表II

思考:快指针(每次2个节点)为什么不会跳过慢指针(每次1个节点)

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast=head
        slow=head
        while  fast and fast.next:
            fast=fast.next.next
            slow=slow.next
            if fast==slow:
                p=fast
                t=head
                while p!=t:
                    p=p.next
                    t=t.next
                return p
        return None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Best,

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值