繁体   English   中英

Python链表无法保存头节点

[英]Python linked list cannot save head node

这是关于一个leetcode问题:“234。回文链接列表”

我想反转链表并将反转与原始列表进行比较。 如果没有差异则返回True。

但奇怪的是,虽然我将头部复制到虚拟节点,但要记录起始位置。 在反转列表后,我无法从虚拟节点迭代,似乎列表中只剩下1个元素。

为什么/如何更新虚拟节点? 这让我很烦,我想把头撞到墙上。

任何帮助表示赞赏!

谢谢!

基于我有限的知识,我已尽力而为。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """


        dummy = head
        prev = None

        while head:
            temp = head
            head = head.next
            temp.next = prev
            prev = temp  

        while prev and dummy:
            print prev.val, dummy.val

            if prev.val != dummy.val:
                return False

            prev = prev.next
            dummy = dummy.next

        return True

我希望上面的代码能够正常工作

从您的代码中,我认为您的想法是反向链接列表,并与原始列表进行比较,但这样做是不正确的。 因为您更改原始链接列表,您不能再进行比较,所以您必须复制,但这是一个低效的解决方案。

我根据您的代码编辑了copy version ,它可以工作,但这不是最好的方法。

def isPalindrome(self, head):
    dummy = head
    prev = None
    cur = origin = ListNode(0)

    # copy the original linkedlist
    while head:
        cur.next = ListNode(head.val)
        head = head.next
        cur = cur.next

    head = dummy
    while head:
        temp = head
        head = head.next
        temp.next = prev
        prev = temp

    cur = origin.next
    while prev and cur:
        print(prev.val, cur.val)

        if prev.val != cur.val:
            return False

        prev = prev.next
        cur = cur.next

    return True

更好的做法是反转LinkList的前半部分,并比较上半部分是否等于下半部分:

def isPalindrome(self, head):
    if not head or not head.next:
        return True
    count, cur = 0, head
    while cur:
        cur = cur.next
        count += 1

    pre, cur, post = None, head, head.next
    for _ in range(count // 2):
        cur.next = pre
        pre, cur, post = cur, post, post.next
    head.next = cur

    slow = pre
    fast = cur.next if count % 2 else cur

    for _ in range(count // 2):
        if slow.val != fast.val:
            return False
        slow, fast = slow.next, fast.next

    return True

更优雅的版本,但不那么容易理解:

def isPalindrome(self, head):
    check = None
    slow = fast = head
    # traverse and reverse
    while fast and fast.next:
        fast = fast.next.next
        check, check.next, slow = slow, check, slow.next

    if fast:
        slow = slow.next
    while slow and slow.val == check.val:
        slow = slow.next
        check = check.next
    return not check

希望对您有所帮助,并在您有其他问题时发表评论。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM