java:用两个栈模拟队列《剑指offer》

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dian1pei2xiao3/article/details/83044908

 

package tulun.stack20181014;

import java.util.Stack;

public class Queue<T> {
    /**
     * 用两个栈模拟队列:
     * 队列先进先出
     * 栈后进先出
     */
        Stack<T> stack1=new Stack<T>();
        Stack<T>  stack2=new Stack<T>();

    /**
     * 借助两个空的栈,入队操作,即先在stack1中push元素,要出队,根据先进先出原则,将stack1中的元素pop到stack2中,此时stack2中的元素即为出      *队顺序,需要出队pop,只需在stack2中pop元素,即为对头元素;说白了,stack2中的栈顶指针一直指向队头元素,只需返回即可
     *
     */
    public void push(T value) {//入队操作
        stack1.push(value);
    }
    public T pop() {//出队操作
            T temp;
            if (!stack2.empty()) {
                return stack2.pop();
            } else {
                while (!stack1.empty()) {
                    temp = stack1.pop();
                    stack2.push(temp);
                }
                return stack2.pop();

            }
        }


        public static void main(String args[]){//测试代码
            Queue <People> st=new Queue<>();
            People P1=new People("zs",12);
            People P2=new People("LS",13);
            People P3=new People("WU",14);

            People P4=new People("zy",15);
            st.push(P1);//入队
            st.push(P2);
            st.push(P3);
            System.out.println(st.pop());//出队并打印对头元素
            System.out.println(st.stack2.peek());
            st.push(P4);
            System.out.println( st.stack1.empty());

        }
    }
    class People{
        private String name;
        private int id;

        public People(String name, int id) {
            this.name = name;
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "People{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    '}';
        }
    }



代码测试结果: 

People{name='zs', id=12}
People{name='LS', id=13}
false

猜你喜欢

转载自blog.csdn.net/Dian1pei2xiao3/article/details/83044908