您的位置:首页 > 编程语言 > Java开发

(java)两个队列实现栈的操作

2016-03-25 11:10 513 查看
(关键思想是要把两个队列想成是联通的,即要来回倒数据)

代码如下:

<span style="font-size:18px;">class MyStack {
// Push element x onto stack.
Queue<Integer> q1=new LinkedList<Integer>();
Queue<Integer> q2=new LinkedList<Integer>();
public void push(int x) {
q1.offer(x);
while(!q2.isEmpty()){
q1.offer(q2.poll());
}
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
}

// Removes the element on top of the stack.
public void pop() {
while(!q2.isEmpty()){
q1.offer(q2.poll());
}
q1.poll();
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
}

// Get the top element.
public int top() {
if(!q2.isEmpty()){
return q2.peek();
}
return -1;
}

// Return whether the stack is empty.
public boolean empty() {
if(q1.isEmpty() && q2.isEmpty()){
return true;
}else{
return false;
}
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法