算法训练Day04 | 24. 两两交换链表中的节点、19.删除链表的倒数第N个节点、 链表相交、142.环形链表II

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

题目链接:24. 两两交换链表中的节点-力扣(LeetCode)

思路:使用虚拟头节点,方便进行节点变换,注意交换节点不能只关注当前两个节点的交换,还需要连接到后一个节点

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre_node = ListNode(next=head)

        while pre_node.next and pre_node.next.next:
            next_node = pre_node.next
            pre_node.next = next_node.next
            next_node.next = next_node.next.next
            pre_node.next.next = next_node
            if next_node == head:
                head = pre_node.next
            pre_node = next_node
        return head

参考文章:代码随想录-24. 两两交换链表中的节点

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

题目链接:19.删除链表的倒数第N个节点-力扣(LeetCode)

思路:双指针思想,先确定距离,再同时移动两个指针,保证后一个指针到达尾部时,前一个指针正在前n+1个

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        left = ListNode(next = head)
        right = left
        for i in range(n):
            right = right.next
            if right is None:
                return -1
        while right.next:
            left = left.next
            right = right.next
        if left.next == head:
            return head.next
        left.next = left.next.next
        return head

参考文章:代码随想录-19.删除链表的倒数第N个节点

面试题 02.07. 链表相交

题目链接:面试题 02.07. 链表相交-力扣(LeetCode)

思路:其实和上一题双指针的思路是有点类似的,都是先确定差值,再同时移动,要点在于确定两个指针的位置

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        len_A, len_B = 0, 0
        temp = headA
        while temp:
            len_A += 1
            temp = temp.next
        temp = headB
        while temp:
            len_B += 1
            temp = temp.next
        temp_B = headB
        temp_A = headA
        if len_A <= len_B: 
            for _ in range(len_B-len_A):
                temp_B = temp_B.next  
        else:
            for _ in range(len_A-len_B):
                temp_A = temp_A.next
        while temp_A != temp_B:
            temp_A = temp_A.next
            temp_B = temp_B.next
        return temp_A

参考文章:代码随想录-面试题 02.07. 链表相交

142.环形链表II

题目链接:142.环形链表II-力扣(LeetCode)

思路:想到了集合的做法,O(1)的做法真没想出来,数学太难了,可以参考代码随想录的详解,链接见文末

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        visited = set()

        while head:
            if head in visited:
                return head
            visited.add(head)
            head = head.next
        return None
        

参考文章:代码随想录-142.环形链表II

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值