簡體   English   中英

如何在保持原始鏈表不變的情況下反轉鏈表

[英]How to reverse a linked list while keeping the original linked list unchanged

如何反轉鏈表保持原始不變? 如果我正在反轉鏈接列表,它也會更改原始鏈接列表。

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        p = head
        q = self.reverse_list(head)
        
       
        while p and q:     
            if p.val != q.val:
                return False
            else:
                p = p.next
                q= q.next
        return True
            
        
    def reverse_list(self, head):
        curr = head
        prev = None
        while curr is not None:
            tmp = curr.next
            curr.next = prev
            prev = curr
            curr = tmp
            
        return prev

您可以使用遞歸制作一個非常美觀(但在 python 中不是超級有效的解決方案)。 基本上,您可以切換遞歸順序,給您一個正向生成器和一個反向生成器,然后是 zip 並進行比較

class Solution:
    def isPalindrome(self, head):
        return all(a.val == b.val 
                   for a,b 
                   in zip(self.forward(head), self.backward(head)))
            
    def forward(self, head):
        if head is None:
            return
        yield head
        yield from self.forward(head.next)


    def backward(self, head):
        if head is None:
            return 
        yield from self.backward(head.next)
        yield head

這很有吸引力,但由於遞歸限制,不太可能處理非常大的列表。

對於更大的輸入,您可以制作forward()生成器的非遞歸版本並從中呈現列表。 然后將列表與其相反的列表進行比較:

class Solution:
    def isPalindrome(self, head):
        v = list(self.forward(head))
        return v == v[::-1]
            
    def forward(self, head):
        while head:
            yield head.val
            head = head.next

這使用 O(n) 空間,但應該表現得相當好。

另一種解決方案是遍歷列表,添加parent屬性為 go。 最后,您將擁有列表的尾部,並且可以並行跟隨父引用再次從頭部運行列表並進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM