225. Stack two queues implemented

implement-stack-using-queues

Title described
using the following queues implemented stack:

push (x) - x elements onto the stack
pop () - remove the top of the stack
top () - Gets the top element
empty () - Returns whether the stack is empty

Note:
You can only use the basic operation of the queue - that is, push to back, peek / pop from front, size, and is empty of these operations are legal.
The language you are using may not support queue. You can use the list or the deque (deque) to simulate a queue, the queue as long as the operation to the standard.
You may assume that all operations are valid (for example, to an empty stack does not call the pop operation or top).

Code

package pid225;
import java.util.LinkedList;
import java.util.Queue;

public class MyStack {
	private Queue<Integer> q1;//存储栈中元素
	private Queue<Integer> q2;//作为一个过渡
	private int top;
	public MyStack(){
		q1 = new LinkedList<>();
		q2 = new LinkedList<>();
	}
	public void push(int x){
		q1.add(x);
		top = x;
	}
	public int pop(){
		while(q1.size()>1){//拷贝到剩余一个元素
			top = q1.remove();
			q2.add(top);
		}
		int res = q1.remove();
		Queue<Integer> temp = q1;
		q1 = q2;
		q2 = temp;
		return res;
	}
	public int top(){
		while(q1.size()>0){//全部拷贝
			top = q1.remove();
			q2.add(top);
		}
		//下面这三步虽然在本问题中似乎无用,但是是对引用的维护,避免本方法影响到其它方法
		Queue<Integer> temp = q1;
		q1 = q2;
		q2 = temp;
		return top;
	}
	public boolean empty(){
		return q1.isEmpty();
	}
}

Performance
Performance

Published 75 original articles · won praise 0 · Views 1521

Guess you like

Origin blog.csdn.net/qq_34087914/article/details/104078639
Recommended