Destructive Stack Iteration

后端 未结 3 634
青春惊慌失措
青春惊慌失措 2021-01-13 15:54

This is my Stack implementation.

class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node          


        
3条回答
  •  盖世英雄少女心
    2021-01-13 16:53

    The problem is that you do not make a difference between the iterable Stack itself and the iterator that __iter__ should return. __next__ should be called on said iterator, not on the Stack itself.

    I propose the following solution:

    class StackIterator:
        def __init__(self, stack):
            self.head = stack.head
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if not self.head:
                raise StopIteration
    
            current = self.head
            self.head = self.head.next
    
            return current.val
    

    Get rid of __next__ in Stack and adjust __iter__ to:

    def __iter__(self):
        return StackIterator(self)
    

    Demo:

    >>> stack = Stack()
    >>> stack.push(12)
    >>> stack.push(13)
    >>> stack.push(9)
    >>> 
    >>> for x in stack:
    ...     print(x)
    ... 
    9
    13
    12
    >>> stack.peek()
    9
    

提交回复
热议问题