代码随想录算法训练营第四天| 24. 两两交换链表中节点、19. 删除链表倒数第N个结点、面试题02.07链表相交、142. 环形链表II

24、两两交换链表中结点

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode()
        dummy.next = head
        cur = dummy.next
        pre = dummy
        while cur:
            if cur.next:
                temp = cur.next.next
                cur.next.next = cur
                pre.next = cur.next
                cur.next = temp
                pre = cur
                cur = temp
            else:
                break
        return dummy.next

只用一个cur节点也可以,不过我嫌next接的太多,就加了pre指针看起来清爽点,主要是虚拟头节点的使用,判断好什么时候循环就行

19、删除链表倒数第N个结点

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode()
        dummy.next = head
        slow, fast = 0, 0
        cur = dummy.next
        while cur:
            if cur.next:
                fast += 1
            cur = cur.next
        cur = dummy
        for i in range(fast+1):
            if slow == fast+1-n:
                cur.next = cur.next.next
                return dummy.next
            cur = cur.next
            slow += 1

用笨方法AC了,这题真正的解法应用快慢指针法一遍扫描过,巧妙且简洁

面试题02.07 链表相交

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        dummyA = ListNode()
        dummyA.next = headA
        cur = dummyA.next
        hash_map = {}
        count = 0
        while cur:
            hash_map[cur] = count
            cur = cur.next
            count += 1
        dummyB = ListNode()
        dummyB.next = headB
        cur = dummyB.next
        inter_node = None
        while cur:
            if cur in hash_map:
                inter_node = cur
                break
            cur = cur.next
        return inter_node

用的哈希表存放已遍历过的节点这个方法,还可以先利用尾结点是否一致判断相交与否,再用长度差异走快慢指针法找出相交结点

142、环形链表II

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode()
        dummy.next = head
        hash_map = {}
        cur = dummy
        index = 0
        while cur.next:
            if cur.next not in hash_map:
                hash_map[cur.next] = index
            else:
                return cur.next
            cur = cur.next
            index += 1

用的哈希表解决,非常简单,不过用快慢指针法解更有技巧性,两个方法最好都掌握

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值