Java中的堆栈实现

时间:2016-07-30 20:37:44

标签: java data-structures stack

我正在尝试使用Java中的Arrays实现堆栈。我的Stack类包含非静态方法push,pop,peek和isempty。我想测试堆栈实现是在主类中的非静态main方法中实例化堆栈。当我尝试这样做时,我收到错误“非静态方法push(int)无法从静态上下文引用” 我做错了什么?

Stack.java

public class Stack {

private int top;
private int[] storage;

Stack(int capacity){
    if (capacity <= 0){
        throw new IllegalArgumentException(
                "Stack's capacity must be positive");
    }
    storage = new int[capacity];
    top = -1;
}

void push(int value){
    if (top == storage.length)
        throw new EmptyStackException();
    top++;
    storage[top] = value;
}

int peek(){
    if (top == -1)
        throw new EmptyStackException();
    return storage[top];
}

int pop(){
    if (top == -1)
        throw new EmptyStackException();
    return storage[top];
  }
}

Main.java

public class Main {

public static void main(String[] args) {
    new Stack(5);
    Stack.push(5);
    System.out.println(Stack.pop());

 }
}

1 个答案:

答案 0 :(得分:1)

您已经创建了一个新实例,但没有在任何地方保存该引用,因此您在创建后立即将其丢失。相反,您应该将其分配给变量,然后在其上应用方法:

public static void main(String[] args) {
    Stack stack = new Stack(5);
    stack.push(5); // invoked on an instance "stack"
    System.out.println(stack.pop());
}