面试题7:用两个栈实现队列

来源:互联网 发布:手机期货交易模拟软件 编辑:程序博客网 时间:2024/05/30 23:36

题目:用两个栈实现一个队列。


思路:添加时只有一种情况,将元素直接压入栈1,删除时有两种情况,第一种情况栈2为空,此时需要先将栈1的所有元素压入栈2,然后清空栈1,并将栈2的栈顶元素出栈,第二种情况是栈2不为空,此时直接将栈2的栈顶元素出栈即可。


C++:

#include <iostream>#include <stack>using namespace std; template<typename T>class CQueue{public:CQueue(void);~CQueue(void);void appendTail(const T& node);T deleteHead();private:stack<T> stack1;stack<T> stack2;};template<typename T>void CQueue<T>::appendTail(const T& element){//添加的时候入栈1stack1.push(element);}template<typename T>T CQueue<T>::deleteHead(){//删除的时候先判断栈2是否为空if(stack2.size()<=0){//栈2为空的时候先将栈1的元素压入栈2while(stack1.size()>0){T & data=stack1.top();stack1.pop();stack2.push(data);}}if(stack2.size()==0){throw new exception("queue is empty");}//从栈2的栈顶开始出栈T head=stack2.top();stack2.pop();return head;}

Java:

public class QueueTest {public static void main(String[] args){Queue<Integer> queue=new Queue<Integer>();queue.push(1);queue.push(2);queue.push(3);Integer result=queue.pop();System.out.println(result);}public static class Queue<T>{private Stack<T> stack1=new Stack<T>();private Stack<T> stack2=new Stack<T>();//添加元素public void push(T item){stack1.push(item);}public T pop(){T item=null;//如果栈2为空if(stack2.empty()){//如果栈1不为空,先将栈1的元素压入栈2while(!stack1.empty()){item=stack1.pop();stack2.push(item);}}//如果栈2不为空,将栈顶元素删除if(!stack2.empty()){item=stack2.pop();}else{System.out.println("栈为空!不能再删除!");}return item;}}}


0 0
原创粉丝点击