新手练手感--part1.1 栈与队列之用栈实现队列的功能

题目:

  用两个stack实现que的add,poll,peek的功能

思路:

stackPush add stackPop
1   5
2   4
3   3
4   2
5   1

(1)stackPush:用来且只用来插入数据

(2)stackPop:用来且只用来取数据

(3)add():stackPush.push()

(4)poll():执行stackPop.pop()。若stackPop为空,将stackPush中元素倒入stackPop。

(5)peer():执行staPop.pop()。若stackPop为空,将stackPush中元素倒入stackPop。

 

写代码:

public class TestCode {
    //存放栈数据
    private Stack<Integer> stackPush = new Stack<Integer>();
    //存放执行每一步之后的最小值
    private Stack<Integer> stackPop = new Stack<Integer>();

    //push
    public void push(Integer pushNum) {
        stackPush.push(pushNum);
    }

    //pop
    public Integer pop() {
        //一个元素都没有
        if(stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new RuntimeException("stack is empty");
        } else if(stackPop.isEmpty()) {
            //stackPop已经空了,把stackPush中元素倒进来
            while(!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }

        return stackPop.pop();
    }
    //peer
    public Integer peer() {
        //一个元素都没有
        if(stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new RuntimeException("stack is empty");
        } else if(stackPop.isEmpty()) {
            //stackPop已经空了,把stackPush中元素倒进来
            while(!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }

        return stackPop.peek();
    }

    public static void main(String[] args) {
        TestCode testCode = new TestCode();
        for(int i = 0; i <= 6; i++) {
            if(i % 3 == 2) {
                testCode.pop();
            } else {
                testCode.push((int) (Math.random() * 10));
            }

            System.out.print("stack of elements: ");
            for(int j = 0; j < testCode.stackPop.size(); j++) {
                System.out.print(" " + testCode.stackPop.get(j));
            }

            for(int j = testCode.stackPush.size() - 1; j >= 0; j--) {
                System.out.print(" " + testCode.stackPush.get(j));
            }
            System.out.println("  stack peer :" + testCode.peer());

        }
    }

}

 

posted @ 2017-06-06 23:21  jiguojing  阅读(271)  评论(0)    收藏  举报