Python

栈 Python实现

2019-07-31  本文已影响1人  Yuanshuo
The core values of Chinese socialism

栈的顺序表实现

# 栈的顺序表实现

class Stack(object):
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        return self.items.append(item)

    def pop(self):
        return self.items.pop()

    def top(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

if __name__ == '__main__':
    stack = Stack()
    stack.push("Hello")
    stack.push("World")
    stack.push("!")
    print(stack.size())
    print(stack.top())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
3
!
!
World
Hello

栈的链接表实现

# 栈的链接表实现

class SingleNode(object):
    def __init__(self, item):
        self.item = item
        self.next = None

class Stack(object):
    def __init__(self):
        self._head = None

    def isEmpty(self):
        return self._head == None

    def push(self, item):
        node = SingleNode(item)
        node.next = self._head
        self._head = node

    def pop(self):
        cur = self._head
        self._head = cur.next
        return cur.item

    def top(self):
        return self._head.item

    def size(self):
        cur = self._head
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        return count

if __name__ == '__main__':
    stack = Stack()
    stack.push("Hello")
    stack.push("World")
    stack.push("!")
    print(stack.size())
    print(stack.top())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
3
!
!
World
Hello
上一篇下一篇

猜你喜欢

热点阅读