【发布时间】:2016-07-18 12:27:18
【问题描述】:
我正在尝试在 Java 中使用数组作为其核心来实现堆栈。这只是学习和理解堆栈工作原理的目的。
我的想法是使用 Array(而不是 ArrayList)并尝试模仿 Stack 结构。此实现将具有静态大小。有一个以 -1 开头的指针表示空堆栈。指针会随着我们添加元素而增加,我们不必担心删除元素,因为一旦我们需要该空间(索引),我们将覆盖该值。
以下是我的源代码,后面还有一些问题:
import java.util.*;
public class stackUsingArray{
private int[] myStack;
private int pointer;
/**
-Constructor
*/
public stackUsingArray()
{
myStack = new int[10];
pointer = -1;//keep track of where the top element is on the stack.
}
/**
-Pop method
*/
public int pop()
{
if(pointer==-1)
{
//throw exception here
}
return myStack[pointer--];
}
/**
-Push when the stack is not empty.
*/
public void push(int num)
{
if(pointer== myStack.size()-1)
{
//throw exception here
}
else
{
myStack[++pointer] = num;//add to the stack
}
}
/**
-return the top element of the stack
*/
public void peek()
{
return pointer;
}
/**
-return false if there is not more element on the stack
*/
public boolean isEmpty()
{
return (pointer == -1)? true : false;
}
public static void main(String [] arg)
{
stackUsingArray newStack = new stackUsingArray();
newStack.push(1);
newStack.push(2);
newStack.push(3);
System.out.println(newStack.pop());
}
}
在我注释为抛出异常的部分:
public int pop()
{
if(pointer==-1)
{
//throw exception here
}
return myStack[pointer--];
}
您认为哪种例外情况最合乎逻辑?大多数时候,我只是在屏幕上打印出来。不过,我很想学习如何抛出异常。
这部分:
public void push(int num)
{
if(pointer== myStack.size()-1)
{
//throw exception here
}
else
{
myStack[++pointer] = num;//add to the stack
}
}
程序本身必须执行 myStack.size() -1 的操作。我想知道在班级中有一个私人成员来保持大小-1是否更好?我的意思是效率。
另外,如果我们要使用 ArrayList 来实现这个 Stack。它会更有效地运行吗?我的意思是,ArrayList 有很多开销,例如方法的内部调用。
最后,我知道我的代码不是很好,所以请给我一些建议,让它变得更好!
【问题讨论】:
-
你知道 Java 已经有一个 Stack 类吗? tutorialspoint.com/java/java_stack_class.htm
-
@SPlatten 他只是想更好地了解它的工作原理。
-
@SPlatten U 在提问之前应该先阅读我写的内容。无论如何,谢谢你的链接。
-
@indjev99 : 谢谢你给他解释,哈哈!
标签: java arrays algorithm performance data-structures