Leetcode--225. 用队列实现栈(Java)
使用隊(duì)列實(shí)現(xiàn)棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
注意:
你只能使用隊(duì)列的基本操作-- 也就是?push to back, peek/pop from front, size, 和?is empty?這些操作是合法的。
你所使用的語(yǔ)言也許不支持隊(duì)列。?你可以使用 list 或者 deque(雙端隊(duì)列)來(lái)模擬一個(gè)隊(duì)列?, 只要是標(biāo)準(zhǔn)的隊(duì)列操作即可。
你可以假設(shè)所有操作都是有效的(例如, 對(duì)一個(gè)空的棧不會(huì)調(diào)用 pop 或者 top 操作)。
思路:插入的時(shí)候模擬棧,先將本次需要插入的數(shù)插入尾部
之后把其他的數(shù)依次從頭部移出并插入尾部,就可以實(shí)現(xiàn)
刪除的時(shí)候因?yàn)橐呀?jīng)逆序,直接刪除即可
代碼:
class?MyStack?{
????public?Queue<Integer>?queue;
????/**?Initialize?your?data?structure?here.?*/
????public?MyStack()?{
????????queue?=?new?LinkedList();
????}
????
????/**?Push?element?x?onto?stack.?*/
????public?void?push(int?x)?{
????????queue.add(x);
????????int?size?=?queue.size();
????????while(size>1)
????????{
????????????queue.add(queue.poll());
????????????size--;
????????}
????}
????
????/**?Removes?the?element?on?top?of?the?stack?and?returns?that?element.?*/
????public?int?pop()?{
????????return?queue.poll();
????}
????
????/**?Get?the?top?element.?*/
????public?int?top()?{
????????return?queue.peek();
????}
????
????/**?Returns?whether?the?stack?is?empty.?*/
????public?boolean?empty()?{
????????return?queue.size()==0;
????}
}
?
/**
?*?Your?MyStack?object?will?be?instantiated?and?called?as?such:
?*?MyStack?obj?=?new?MyStack();
?*?obj.push(x);
?*?int?param_2?=?obj.pop();
?*?int?param_3?=?obj.top();
?*?boolean?param_4?=?obj.empty();
?*/
總結(jié)
以上是生活随笔為你收集整理的Leetcode--225. 用队列实现栈(Java)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PHP中foreach遍历循环的使用(两
- 下一篇: html表格ui,table表格 - 基