代码随想录算法训练营第四日|LC24:两两交换链表中的节点,LC19:删除链表的倒数第N个节点, 面试题 02.07. 链表相交 ,142.环形链表II

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

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0)
        dummy.next = head
        cur = dummy
        while cur.next is not None and cur.next.next is not None:
            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 dummy.next

画图!画图!画图!要不然很容易绕进去,定义虚拟节点事半功倍!

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

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

        while n != 0:
            fast = fast.next
            n -= 1
        while fast.next != None:
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next
        return dummy.next

快慢双指针!要想清楚快指针先走n步,然后快慢指针再同时走,这样当快指针的next指向结尾None时,慢指针刚好在第N-1的位置,然后直接删除第N个节点就行了!

面试题 02.07. 链表相交:

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        cur_a, cur_b = headA, headB
        while cur_a != cur_b:
            cur_a = cur_a.next if cur_a else headB
            cur_b = cur_b.next if cur_b else headA
        return cur_a

定义两个节点,从各自链表的头节点开始走,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个 位置相遇!

142.环形链表II:

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast = head
        slow = head
        while fast is not None and fast.next is not None:
            fast = fast.next.next
            slow = slow.next

            if fast == slow:
                index1 = fast
                index2 = head
                while index1 != index2:
                    index1 = index1.next
                    index2 = index2.next
                return index1
        return None

  快慢双指针,fast每次两步,slow每次一步。当fast等于slow时说明链表有环,将当前相遇点定义为index1,头节点为index2,两点相遇为入环交点。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值