【问题标题】:TLE error when swapping nodes in linked list交换链表中的节点时出现 TLE 错误
【发布时间】:2020-03-15 00:37:40
【问题描述】:

我正在尝试在 leetcode (https://leetcode.com/problems/swap-nodes-in-pairs/) 上“成对交换节点”。

我的代码如下。它仅对 1 个测试用例产生 TLE 错误。我真的不确定它是否陷入无限循环。感谢任何帮助。

def swapPairs(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    ans=h=ListNode(0)
    while head and head.next:
        h.next=head.next
        h.next.next=head
        h=h.next.next
        head=head.next.next
    h.next=head
    return ans.next

【问题讨论】:

  • 嗨@Tommy。请查看我的解决方案,如果它有帮助以及您有任何问题,请告诉我。谢谢。

标签: python linked-list


【解决方案1】:

我在您的代码中看到的问题是h.next.next=head 的这一行。我假设您正在尝试设置相邻节点,但实际上这实际上是在第一次运行时将整个列表设置为h.next.next。反过来,这又在head=head.next.next 处再次设置,然后就像您所怀疑的那样简单地导致无限递归。

既然你已经掌握了关键点,我希望你能纠正你的错误并实施你的解决方案。

我已经重新实现了您对以下问题的解决方案。

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or head.next == None:
            return head
        first = cur = ListNode(0) #initialize a node object with 0 value
        cur.next = head #get accesss to the first node

        while (cur.next and cur.next.next):
            a = cur.next
            b = cur.next.next
            c = cur.next.next.next

            #swap the nodes here
            cur.next = b
            cur.next.next = a
            cur.next.next.next = c
            cur = cur.next.next # sets it to one before the next node

        return first.next  

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 2017-12-07
    • 2018-11-05
    • 1970-01-01
    • 2015-05-28
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多