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"]

posted on 2010-01-17 10:40  小橋流水  阅读(192)  评论(0编辑  收藏  举报

导航