码迷,mamicode.com
首页 > 其他好文 > 详细

用队列实现栈

时间:2019-05-02 21:22:57      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:The   etc   int   bool   com   htm   操作   ack   ret   

小结:

1、

借助linkedlist,每次添加元素后,反转,取逆序

 

Implement Stack using Queues - LeetCode
https://leetcode.com/problems/implement-stack-using-queues/solution/

Implement Stack using Queues - LeetCode Articles
https://leetcode.com/articles/implement-stack-using-queues/

使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

注意:

  • 你只能使用队列的基本操作-- 也就是 push to backpeek/pop from frontsize, 和 is empty 这些操作是合法的。
  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

 

Approach #1 (Two Queues, push - O(1), pop O(n))

技术图片

Approach #2 (Two Queues, push - O(n), pop O(1) )

技术图片

Approach #3 (One Queue, push - O(n), pop O(1))

技术图片

 

package leetcode;

import java.util.LinkedList;
import java.util.Queue;

class MyStack {

//one Queue solution
private Queue<Integer> q = new LinkedList<Integer>();

public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(-2);
myStack.push(0);
myStack.push(-3);
myStack.push(13);
myStack.pop();
myStack.top();
}

// Push element x onto stack.
public void push(int x) {
q.add(x);
for (int i = 1; i < q.size(); i++) { //rotate the queue to make the tail be the head
q.add(q.poll());
}
}

// Removes the element on top of the stack.
public int pop() {
return q.poll();
}

// Get the top element.
public int top() {
return q.peek();
}

// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}

 

用队列实现栈

标签:The   etc   int   bool   com   htm   操作   ack   ret   

原文地址:https://www.cnblogs.com/yuanjiangw/p/10803322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!