代码随想录算法训练营第4天 | 链表(24 两两交换链表中的节点 19 删除链表的倒数第N个节点 160 链表相交 142 环形链表II)

本文介绍了四个链表相关的算法问题:如何两两交换链表中的节点,删除链表的倒数第N个节点,找到两个链表的交点以及检测环形链表。所有解决方案都具有O(n)的时间复杂度和有限的空间复杂度,利用快慢指针或栈来高效解决问题。
摘要由CSDN通过智能技术生成

24 两两交换链表中的节点

 

class Solution(object):
    def swapPairs(self, head):
        dummy_head = ListNode()
        dummy_head.next = head
        prev = dummy_head
        while prev.next and prev.next.next:
            node1 = prev.next
            node2 = prev.next.next

            node1.next = node2.next
            node2.next = node1
            prev.next = node2
            prev = node1
        return dummy_head.next
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

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

  • fast slow 

class Solution(object):
    def removeNthFromEnd(self, head, n):
        dummy_head = ListNode()
        dummy_head.next = slow = fast = head
        prev = dummy_head
        for _ in range(n):
            fast = fast.next
        while fast:
            prev = slow
            slow = slow.next
            fast = fast.next
        prev.next = slow.next
        return dummy_head.next
  • 时间复杂度:O(n)
  • 空间复杂度:O(1) 

160 链表相交  

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        stackA = []
        stackB = []
        if not headA or not headB:
            return None
        
        while headA:
            stackA.append(headA)
            headA = headA.next
        headA = stackA.pop()
        while headB:
            stackB.append(headB)
            headB = headB.next
        headB = stackB.pop()

        while stackA and stackB and headA == headB:
            headA = stackA.pop()
            headB = stackB.pop()
        if not stackA and headA == headB:
            return headA
        elif not stackB and headA == headB:
            return headB
        return headA.next
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

142 环形链表II

  • fast slow

class Solution(object):
    def detectCycle(self, head):
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                break
        if not fast or not fast.next:
            return None
        cur = head
        while cur != slow:
            cur = cur.next
            slow = slow.next
        return cur
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值