剑指offer题五

来源:互联网 发布:解忧杂货店淘宝 编辑:程序博客网 时间:2024/05/18 16:14
package jianzhioffer;import java.util.ArrayList;import java.util.List;import java.util.Stack; /** * 用两个栈实现队列的出入栈,栈A用来作入队列,栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列) * */public class StacktoQueue {     Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();        public void push(int node) {        stack1.push(node);    }        public int pop() {        if(stack1.empty() && stack2.empty()){        throw new RuntimeException("Queue is empty!");        }        if(stack2.empty()){        while(!stack1.empty()){        stack2.push(stack1.pop());        }        }        return stack2.pop();    }    public static void main(String[] args) {StacktoQueue sq = new StacktoQueue();List<Integer> list = new ArrayList<Integer>();sq.push(1);sq.push(2);sq.push(3);list.add(sq.pop());sq.push(4);list.add(sq.pop());sq.push(5);list.add(sq.pop());list.add(sq.pop());list.add(sq.pop());System.out.println(list.toString());}    }
package jianzhioffer;import java.util.LinkedList;import java.util.Queue;/** * 两个队列实现一个栈 出入功能 * */public class QueuetoStack { LinkedList<Integer> queue1 = new LinkedList<Integer>();LinkedList<Integer> queue2 = new LinkedList<Integer>();public Integer pop(){Integer re = null;if(queue1.size() ==0 && queue2.size() ==0){return null;}if(queue2.size()==0){while(queue1.size()>0){re=queue1.removeFirst();if(queue1.size()!=0){//do not add the last element of queue1 to queue2  queue2.addLast(re);}}}else if (queue1.size() ==0){while(queue2.size()>0){re = queue2.removeFirst();if(queue2.size() != 0){//do not add the last element of queue2 to queue1  queue1.addLast(re);}}}return re;}public Integer push(Integer node){if(queue1.size() == 0 && queue2.size() == 0){queue1.addLast(node);}if(queue1.size() != 0){queue1.addLast(node);}else if(queue2.size() != 0){queue2.addLast(node);}return node;}public static void main(String[] args) {QueuetoStack qs = new QueuetoStack();int tmp = 0;qs.push(1);qs.push(2);qs.push(3);tmp = qs.pop();System.out.println(tmp);//3qs.push(4);tmp = qs.pop();System.out.println(tmp);//4qs.push(5);qs.push(6);tmp = qs.pop();System.out.println(tmp);//6tmp = qs.pop();System.out.println(tmp);//5tmp = qs.pop();System.out.println(tmp);//2tmp = qs.pop();System.out.println(tmp);//1}}


原创粉丝点击