我创建了这个非常简单的堆栈概念的实现。你能告诉我它是否正确和干净吗?您是否看到任何不良的编码习惯?
public class MyStack
{
private static final int MAXELEMENTS = 10;
private int[] elements;
private int numElements;
public MyStack()
{
numElements = 0;
elements = new int[MAXELEMENTS];
}
public boolean isEmpty()
{
return (numElements == 0);
}
public boolean isFull()
{
return (numElements == MAXELEMENTS);
}
public void push(int e)
{
if (!isFull())
elements[numElements++] = e;
}
public int top()
{
if (!isEmpty())
return elements[numElements - 1];
else
return -1;
}
public void pop()
{
if (!isEmpty())
numElements--;
}
}
您可以将其与以下代码一起使用:
class MyStackTestDrive
{
public static void main(String[] args)
{
MyStack s1 = new MyStack();
MyStack s2 = new MyStack();
s1.push(2);
s2.push(4);
System.out.println(s1.top());
System.out.println(s2.top());
}
}