标签:
题目链接:https://leetcode.com/problems/implement-stack-using-queues/
题目:Implement the following operations of a stack using queues.
push
to back, peek/pop from front, size,
and is empty operations are valid.public class Solution
{
Queue<Integer> q1=new ArrayDeque<>();
Queue<Integer> q2=new ArrayDeque<>();
// Push element x onto stack.
public void push(int x)
{
if(q1.isEmpty())
{
q1.add(x);
while(!q2.isEmpty())
{
q1.add(q2.poll());
}
}
else
{
q2.add(x);
while(!q1.isEmpty())
{
q2.add(q1.poll());
}
}
}
// Removes the element on top of the stack.
public void pop()
{
if(!q1.isEmpty())
q1.poll();
if(!q2.isEmpty())
q2.poll();
}
// Get the top element.
public int top()
{
if (!q1.isEmpty())
return q1.peek();
if (!q2.isEmpty())
return q2.peek();
else
return -1;
}
// Return whether the stack is empty.
public boolean empty()
{
return q1.isEmpty() && q2.isEmpty();
}
}
【LeetCode OJ 225】Implement Stack using Queues
标签:
原文地址:http://blog.csdn.net/xujian_2014/article/details/50747683