python实现的链表栈
Stack
class EmptyStackException(Exception):
pass
class Element:
def __init__(self, value, next):
self.value = value
self.next = next
class Stack:
def __init__(self):
self.head = None
def push(self, element):
self.head = Element(element, self.head)
def pop(self):
if self.empty(): raise EmptyStackException
result = self.head.value
self.head = self.head.next
return result
def empty(self):
return self.head == None
if __name__ == "__main__":
stack = Stack()
elements = ["first", "second", "third", "fourth"]
for e in elements:
stack.push(e)
result = []
while not stack.empty():
result.append(stack.pop())
assert result == ["fourth", "third", "second", "first"]
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。