Destructive Stack Iteration

后端 未结 3 604
青春惊慌失措
青春惊慌失措 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:34

    Because you can have more than one iterator on the same stack, __iter__ has to return a iterator-object, that iterates the stack:

    class Stack:
        def __init__(self):
            self.head = None
            self.size = 0
    
        def push(self, item):
            node = Node(item)
            if self.head:
                node.next = self.head
            self.head = node
            self.size += 1
    
        def pop(self):
            if self.size == 0:
                raise ValueError('Popping off an empty stack!')
            item = self.head.val
            self.head = self.head.next
            return item
    
        def peek(self):
            if self.size == 0:
                raise ValueError('Peeking into an empty stack!')
            return self.head.val
    
        def __iter__(self):
            return StackIterator(self.head)
    
    class StackIterator:
        def __init__(self, head):
            self.head = head
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if not self.head:
                raise StopIteration()
            item = self.head.val
            self.head = self.head.next
            return item
    

提交回复
热议问题