- 用栈实现队列
分析:
- 声明两个栈s1和s2,每次push将元素push到s1中,每次pop检查s2是否为空,若不为空直接pop;若s2为空,则检查s1是否为空,如果不为空则将s1的全部元素push到s2中,直到s1为空,然后pop s2的栈顶元素,即s1中最早压入的元素。
- 声明一个栈s,在push元素时,声明一个临时栈,每次push元素时,首先将s中的元素全部push到临时栈中,然后将新元素push到临时栈中,最后将临时栈中的元素全部push到栈s中,因此新压入的元素被压入了栈底。每次pop元素时,直接弹出栈s的栈顶元素。
Stack<Integer> stack1;
Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1=new Stack<>();
stack2=new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if(stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack1.isEmpty()&&stack2.isEmpty())
return true;
return false;
}
private Stack<Integer> stack;
/** Initialize your data structure here. */
public MyQueue() {
stack=new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
Stack<Integer> tempS=new Stack<>();
while(!stack.isEmpty()) {
tempS.push(stack.pop());
}
tempS.push(x);//确保新加入的元素在栈的最顶端
while(!tempS.isEmpty()) {
stack.push(tempS.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int x=-1;
if(empty()==false) {
x=stack.pop();
}
return x;
}
/** Get the front element. */
public int peek() {
int x=-1;
if(empty()==false) {
x=stack.peek();
}
return x;
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack.isEmpty())
return true;
else
return false;
}
- 用队列实现栈
分析:
- 声明一个队列q。每次push元素时,首先将元素push到临时队列中;然后判断队列q是否为空,若不为空则将队列中的元素全部push到临时队列中;然后将临时队列中的元素全部push到q中。pop时直接弹出q的队头元素。
//执行用时 : 86 ms, 在Implement Stack using Queues的Java提交中击败了80.85% 的用户
//内存消耗 : 33.4 MB, 在Implement Stack using Queues的Java提交中击败了92.56% 的用户
private Queue<Integer> queu;
/** Initialize your data structure here. */
public MyStack() {
queu=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
Queue<Integer> tempQ=new LinkedList<>();
tempQ.offer(x);
while(queu.isEmpty()==false) {
tempQ.offer(queu.poll());
}
while(tempQ.isEmpty()==false) {
queu.offer(tempQ.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int x=-1;
if(empty()!=true)
x=queu.poll();
return x;
}
/** Get the top element. */
public int top() {
int x=-1;
if(empty()!=true)
x=queu.peek();
return x;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queu.isEmpty();
}

博客介绍了栈与队列相互实现的方法。用栈实现队列有两种方式,一是借助两个栈s1和s2操作;二是用一个栈s和临时栈操作。用队列实现栈则是声明一个队列q和临时队列,通过元素的转移来实现栈的功能。
30万+

被折叠的 条评论
为什么被折叠?



