栈和队列
用两个栈来实现队列
如有两个栈s1和s2
入队操作:只进行s1入栈
出队操作:判断s2是否为空,如果为空,则把s1中的元素全部压入s2中,在弹出s2中的元素
Java实现代码实例:
public
class
Solution {
Stack<Integer> stack1 =
new
Stack<Integer>();
Stack<Integer> stack2 =
new
Stack<Integer>();
public
void
push(
int
node) {
stack1.add(node);
}
public
int
pop() {
if
(stack2.empty())
{
while
(!stack1.empty()){
stack2.add(stack1.pop());
}
}
return
stack2.pop();
}
}
用两个队列来实现栈
如有两个队列q1和q2
有一个队列专门负责出栈,队列负责数据中转
设置两个指针,一个指向出栈队列(stackQueue),另一个指向中转栈队列(tempQueue)
入栈操作:数据存入出栈队列
出栈操作:出栈队列的数据除了最后一个数据外全部转存到中转对列中,出栈对列的数据出队,完成出栈操作
stackQueue指向原中转栈对列,tempQueue指向原出栈对列
Java实现代码实例:
import java.util.LinkedList;
import java.util.Queue;
//用两个队列实现一个栈
public class QueueAndStack {
Queue<Integer> stackQueue=new LinkedList<Integer>();
Queue<Integer> tempQueue=new LinkedList<Integer>();
public void push(int node)
{
stackQueue.add(node);
}
public Integer pop()
{
while(stackQueue.size()>1)
{
tempQueue.add(stackQueue.poll());
}
Queue<Integer> queue=new LinkedList<Integer>();
queue=tempQueue;
tempQueue=stackQueue;
stackQueue=queue;
return tempQueue.poll();
}
}