java 自己实现 栈 demo (顺序存储)

Java

2017-07-06

32

0

技术:java8

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:java 自己实现 栈 demo (顺序存储)

源代码

http://git.oschina.net/youlixishi/demo-world/blob/master/src/algorithm/binary-search/src/main/java/com/demoworld/JArrayStack.java

 

public class JArrayStack implements IStack {
    private int[] arr;
    private int tailIndex;//当前栈的尾巴索引, 这个位置是最后一个数据
    private int maxLength;

    public JArrayStack(int maxLength) {
        this.maxLength = maxLength;
        arr = new int[this.maxLength];
        tailIndex = -1;
    }


    @Override
    public void push(int n) {
        if (tailIndex + 1 >= arr.length) {
//            System.out.println("warn: queue is full");
            return;
        }
        tailIndex++;
        arr[tailIndex] = n;
    }

    @Override
    public int pop() {
        int result = arr[tailIndex];
        tailIndex--;
        return result;
    }

    @Override
    public boolean isEmpty() {
        return tailIndex == -1;
    }
}

测试类

public class JArrayStackTest {
    //正常的 push pop
    @Test
    public void test1() {
        JArrayStack j = new JArrayStack(2);
        for (int i = 1; i <= 2; i++) {
            j.push(i);
        }

        while (!j.isEmpty()) {
            System.out.println(j.pop());
        }
    }

    //超过最长长度
    @Test
    public void test2() {
        JArrayStack j = new JArrayStack(2);
        for (int i = 1; i <= 10; i++) {
            j.push(i);
            if (i == 5) {
                System.out.println(j.pop());
            }
        }

        while (!j.isEmpty()) {
            System.out.println(j.pop());
        }
    }

    //push pop混合操作
    @Test
    public void test3() {
        JArrayStack j = new JArrayStack(10);
        for (int i = 1; i <= 10; i++) {
            j.push(i);
            if (i == 5) {
                System.out.println(j.pop());
                j.push(12);
            }
        }

        while (!j.isEmpty()) {
            System.out.println(j.pop());
        }
    }
}

 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think