【Leetcode刷题Day4】24两两交换链表中的节点 ,19删除链表的倒数第N个节点,链表相交,142环形链表II

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

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: 
        dummyhead = ListNode(next = head)
        cur = dummyhead
        while cur.next and cur.next.next: #!= None:
            #保存1/3
            temp = cur.next
            temp1 =  cur.next.next.next
            #开始更新
            cur.next = cur.next.next
            cur.next.next = temp
            temp.next = temp1
            #进入下一次循环
            cur = cur.next.next
        return dummyhead.next

19删除链表的倒数第N个节点

采用双指针法棒棒的,先让fast走n步,再让快慢一起走,当fast到了null,slow就到了要删除的节点;为了找到要删除的节点的前一个,快指针走n+1步

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        #这个题也要加个dummyhead,以防去掉的是第一个数
        head_dummy = ListNode()
        head_dummy.next = head
        slow = head_dummy
        fast = head_dummy
        while n != 0:  #
            fast = fast.next
            n -= 1
        while fast.next != None:
            slow = slow.next
            fast = fast.next
            #fast 走到结尾后,slow的下一个节点为倒数第N个节点
        slow.next = slow.next.next
        return head_dummy.next

142环形链表II 

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast = head
        slow = head #双指针来啦
        while fast!= None and fast.next != None:
            fast = fast.next.next #尽情的跳吧,跳两步
            slow = slow.next #跳一步
            if slow == fast:
                index1 = fast
                index2 = head
                #当两个index相等时,正好在环形链表的进入点上
                while index1 != index2:
                    index1 = index1.next
                    index2 = index2.next
                return index1
        return None

链表相交

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):  # 让curA和curB在同一起点上(末尾位置对齐)
            curB = curB.next 
        while curA:         #  遍历curA 和 curB,遇到相同则直接返回
            if curA == curB:
                return curA
            else:
                curA = curA.next 
                curB = curB.next
        return None 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值