簡體   English   中英

如何比較python 3.7中的兩個鏈表?

[英]How do I compare two linked lists in python 3.7?

首先,我當前的代碼:

class linkedlist(object):

    def __init__(self, value, next = None):
        self.value = value
        self.next = next

    def traverse(self):
        field = self
        while field != None:
            print(field.value)
            field = field.next

    def equal(self, other):
        while self and other and self.value== other.value:
            self = self.next
            other = other.next

        if self and other:
            if self.value!= other.value:
                return False
            else:
                return True

我的任務是比較兩個鏈表。 如果它們相同,則“相等”函數應返回“真”,如果不是“假”。 功能負責人必須保持這種狀態。

我試圖自己找到解決方案 3 小時,現在我已經腦殘了。 誰能給我一些提示/幫助? 我不是最好的程序員,所以很抱歉:(

你快到了。 您正在使用正確的策略來遍歷兩個鏈表並跳過任何相等的配對元素(您的第一個循環)。

你出錯的地方是你沒有處理所有可能的場景之后發生的事情。 您現在知道這兩個鏈表具有介於 0 和 N 之間的相等元素的前綴。 您現在可以考慮以下 4 個選項之一:

  1. self已精疲力竭,但other未精疲力竭; other更長所以不相等,返回False
  2. other已精疲力竭,但self卻沒有; self更長所以不相等,返回False
  3. selfother仍然有更多元素,但兩個鏈表的下一個元素具有不相等的值。 返回False
  4. selfother都用盡了,所以長度相等。 它們的前綴是相等的,所以鏈表是相等的。 返回True

您現在只能處理選項 3。 鑒於 4 個場景中有 3 個導致return False ,只測試場景 4 會更容易:

if not self and not other:
    return True
return False

或者,作為一個完整的方法:

def equal(self, other):
    while self and other and self.value == other.value:
        self = self.next
        other = other.next
    if not self and not other:
        return True
    return False

暫無
暫無

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

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