LeetCode:225. 用队列实现栈
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                LeetCode:225. 用队列实现栈
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                1、題目描述
使用隊(duì)列實(shí)現(xiàn)棧的下列操作:
- push(x) -- 元素 x 入棧
 - pop() -- 移除棧頂元素
 - top() -- 獲取棧頂元素
 - empty() -- 返回棧是否為空
 
注意:
- 你只能使用隊(duì)列的基本操作-- 也就是?push to back,?peek/pop from front,?size, 和?is empty?這些操作是合法的。
 - 你所使用的語言也許不支持隊(duì)列。?你可以使用 list 或者 deque(雙端隊(duì)列)來模擬一個隊(duì)列?, 只要是標(biāo)準(zhǔn)的隊(duì)列操作即可。
 - 你可以假設(shè)所有操作都是有效的(例如, 對一個空的棧不會調(diào)用 pop 或者 top 操作)。
 
2、題解
2.1、解法一
class MyStack(object):def __init__(self):"""Initialize your data structure here."""self.stack = []def push(self, x):"""Push element x onto stack.:type x: int:rtype: void"""self.stack.append(x)def pop(self):"""Removes the element on top of the stack and returns that element.:rtype: int"""return self.stack.pop()def top(self):"""Get the top element.:rtype: int"""return self.stack[-1] if self.empty() == False else Nonedef empty(self):"""Returns whether the stack is empty.:rtype: bool"""return len(self.stack) == 0# Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
轉(zhuǎn)載于:https://www.cnblogs.com/bad-robot/p/10066268.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode:225. 用队列实现栈的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: python部分 + 数据库 + 网络编
 - 下一篇: 个人冲刺10