使用 for 循环创建堆栈和遍历堆栈的迭代器

Creating a stack and iterator that runs thorugh the stack using a for loop

我正在尝试使用 LIFO 原则创建堆栈。我可以只使用 push 和 pop 功能来做到这一点。但是我想创建一个 iter 和一个 next 函数来遍历堆栈。以下是我尝试过的,但无法真正弄清楚逻辑。

class Stack:
  def __init__(self):
     self.stack = []
     self.START = None
     self.END = None

def push(self, item):
    self.stack.append(item)
    #print("item added to stack")

def pop(self):
    return self.stack.pop()
    #print("value removed according to LIFO")

def emptystack(self):
    return len(self.stack) == 0

def __iter__(self):
    self.Iterator = self.START
    return self

def __next__(self):
    if self.Iterator != None:
        stack = self.Iterator
        self.Iterator = self.Iterator.NEXT
        return node
    else:
        raise StopIteration


def fullstack(self):
    return self.stack

s = Stack()
s.push('1')
s.push('2')
s.push('6')
s.push('8')
s.push('11')
s.push('12')
s.pop()
s.push('50')
if s.emptystack():
   print("Stack is empty")
else:
   print(s.fullstack())

既然你是list来存储栈元素的,那么你可以用python的iter函数对return迭代器使用

class Stack:

    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.append(item)
    #print("item added to stack")

    def pop(self):
        return self.stack.pop()
    #print("value removed according to LIFO")

    def emptystack(self):
        return len(self.stack) == 0

    def stack_iter(self):
        return iter(self.stack)

    def stack_iter_next(self, iterator):
        return next(self.Iterator)

    def fullstack(self):
        return self.stack

s = Stack()
s.push('1')
s.push('2')
s.push('6')
s.push('8')
s.push('11')
s.push('12')
s.pop()
s.push('50')

s_iter = s.stack_iter()

for x in s_iter:
    print (x)

您的 Iterator 属性将始终为 None,因为您会在第一次调用 next 时立即停止迭代。将 next 视为每个项目都被调用,直到没有更多项目要处理,来自 Python 关于 __next__:

的文档

Return the next item from the container. If there are no further items, raise the StopIteration exception

你可以做的一件事是将 self.Iterator 初始化为堆栈的长度(在 __iter__ 中),然后在每一步中递减它直到达到 0(然后提高 StopIteration):

def __iter__(self):
    self.Iterator = len(self.stack) - 1  # initialize to the index of the last element
    return self

def __next__(self):
    if self.Iterator >= 0:
        current_value = self.stack[self.Iterator]
        self.Iterator = self.Iterator - 1  # update for the next step
        return current_value
    else: # stop if self.Iterator is -1
        raise StopIteration