我有关于堆栈的java代码。我需要帮助来填写下面的方法create method
或create 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;
}
}
答案 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()
,我们top
从0
开始并且长大(参见push()
) - 我们还有一个数组A
。所以,
public boolean isFull()
{
return (top >= A.length);
}