标签: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 to back
, peek/pop from front
, size
, 和 is empty
这些操作是合法的。
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