Java数组栈实现

时间:2014-09-17 04:12:52

标签: java stack pop peek

我有关于堆栈的java代码。我需要帮助来填写下面的方法create methodcreate constructor here

public class ArrayStack
{

    private int[] A;

    private int top;

    public ArrayStack()
    {
        create constructor here
    }

    public ArrayStack(int maxsize)
    {
        create constructor here
    }

    public boolean isEmpty() {
        create method
    }

    public boolean isFull()
    {
        create method
    }

    public int peek()
    {
        if(isEmpty())
            throw new RuntimeException("Peek attempted on empty stack");
        else
            return A[top];
    }

    public void push(int m)
    {
        if(isFull())
            throw new RuntimeException("Push attempted on full stack");
        else
        {
            top++;
            A[top]=m;
        }
    }

    public int pop()
    {
        if(isEmpty())
            throw new RuntimeException("Pop attempted on empty stack");
        else
        {
            int value = A[top];
            top--;
            return value;
        }
    }

    public int size()
    {
        return (top + 1);
    }

    public String toString()
    {
        String answer = "";
        int i;
        for(i = 0; i <= top; i++)
            answer = "\n" + A[i] + answer;
        return answer;
    }

}

1 个答案:

答案 0 :(得分:2)

首先,构造函数需要创建数组A

private int[] A;
private int top = 0;  // <-- start at 0
public ArrayStack()
{
  this(10);           // <-- delegate to the second constructor.
  // A = new int[10]; // <-- OR 
}

public ArrayStack(int maxsize)
{
  A = new int[maxsize];
}

接下来,我将向您展示如何进行其他测试。让我们看看isFull(),我们top0开始并且长大(参见push()) - 我们还有一个数组A。所以,

public boolean isFull()
{
  return (top >= A.length);
}
相关问题