用数组实现栈

2019-05-31  本文已影响0人  成长和自由之路

用数组实现栈,详细代码如下:

package stack;

public class StackByArray {
    String[] arrays;
    int count;
    int index;

    public StackByArray(int n) {
        arrays = new String[n];
        count = n;
        index = 0;
    }

    public boolean push(String item) {
        if (index == count) {
            return false;
        }
        arrays[index] = item;
        index++;
        return true;
    }

    public String pop() {
        if (index == 0) {
            return null;
        }
        String temp = arrays[index - 1];
        index--;
        return temp;
    }

    public String peek() {
        if (index == 0) {
            return null;
        }
        String temp = arrays[index - 1];
        return temp;
    }

    public boolean empty() {
        return index == 0;
    }
}

复杂度分析

时间复杂度 : push 和 pop 均为:O(1)
空间复杂度 : push 和 pop 均为:O(1)

上一篇 下一篇

猜你喜欢

热点阅读