簡體   English   中英

為雙向鏈表實現Iter

[英]Implementing Iter for doubly-linked list

問題:剛接觸python時,我目前正在嘗試學習繩索,以更好地處理數組與鏈接結構之間的區別。 我試圖創建一個鏈接列表類,以幫助更好地理解該語言及其結構。 到目前為止我寫的是:

class LinkedList:
    class Node:
        def __init__(self, val, prior=None, next=None):
            self.val = val
            self.prior = prior
            self.next  = next

    def __init__(self):
        self.head = LinkedList.Node(None) 
        self.head.prior = self.head.next = self.head 
        self.length = 0

    def __str__(self):
        if len(self)==0:
            return '[]'
        else:
            return '[' +  ', '.join(str(x) for x in self) + ']'

    def __repr__(self):
        """Supports REPL inspection. (Same behavior as `str`.)"""
        return str(self)

    def __len__(self):
        """Implements `len(self)`"""
        return self.length

    def __iter__(self):
        """Supports iteration (via `iter(self)`)"""
        cursor = self.head
        while cursor:
            yield cursor.val
            cursor = cursor.next

    def append(self, value):
        n = LinkedList.Node(value, prior=self.head.prior, next=self.head)
        n.prior.next = n.next.prior = n
        self.length += 1

在下面的代碼中進行測試,我將遇到一個問題,即內核任務不會結束,或者調試器將指向失敗的測試代碼的第7行。 我不認為我的__repr__方法是錯誤的,這就是為什么我要問,如何編輯__iter__方法主體以解決此問題? 我以為我要做的就是遍歷游標中的值。

from unittest import TestCase
tc = TestCase()

lst = LinkedList()
for d in (10, 20, 30, 40, 50):
    lst.append(d)
tc.assertEqual('[10, 20, 30, 40, 50]', str(lst))
tc.assertEqual('[10, 20, 30, 40, 50]', repr(lst))

因為您說self.head是前哨節點,所以您的__iter__是不正確的; 它正在測試,好像它希望找到一個“虛假”值(例如None )一樣,當被循環鏈接時,它將永遠不會達到這一點。 大概,您想要這樣的東西:

def __iter__(self):
    """Supports iteration (via `iter(self)`)"""
    cursor = self.head.next  # Must advance past non-valued head
    # Done when we get back to head
    while cursor is not self.head:
        yield cursor.val
        cursor = cursor.next

您有一個循環清單。 我用通常的高科技方法對此進行了診斷:打印報表。 :-)

我在您的str方法中插入了一些圖片:

def __str__(self):
    if len(self)==0:
        return '[]'
    else:
        print "NODE VALUE:", self.head.val
        for x in self:
            print "LIST ITEM", x
        return '[' +  ', '.join(str(x) for x in self) + ']'

...並減少測試的力度:

lst = LinkedList()
for d in (10, 20, 30, 40, 50):
    lst.append(d)
print "str\t", str(lst)

您的方法遍歷五個期望值和一個None標頭。

LIST ITEM None
LIST ITEM 10
LIST ITEM 20
LIST ITEM 30
LIST ITEM 40
LIST ITEM 50
LIST ITEM None
LIST ITEM 10
LIST ITEM 20
LIST ITEM 30
LIST ITEM 40
LIST ITEM 50
LIST ITEM None
LIST ITEM 10
LIST ITEM 20

暫無
暫無

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

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