美文网首页Python
栈 Python实现

栈 Python实现

作者: Yuanshuo | 来源:发表于2019-07-31 17:48 被阅读1次
    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
    

    相关文章

      网友评论

        本文标题:栈 Python实现

        本文链接:https://www.haomeiwen.com/subject/albtdctx.html