我正在尝试在 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 的操作。我在想是不是类(class)里有一个private成员来持有size-1会不会更好?我指的是效率。
另外,如果我们要使用 ArrayList 来实现这个 Stack。运行效率会更高吗?我的意思是,ArrayList 有很多开销,例如方法的内部调用。
最后,我知道我的代码不是很好,所以请给我一些建议,让它变得更好!
最佳答案
我会抛出派生自 RuntimeException 的自定义 StackEmptyException/StackFullException,这样它们就不会被选中。如果未选中,您的用户不必包围 try/catch 中的每个 pop()。如果你抛出一个已检查的异常,他们将不得不尝试/捕获每个 pop,或者将他们自己的方法声明为抛出异常。有关详细信息,请参阅此讨论:Java: checked vs unchecked exception explanation
The program itself has to do the operation of myStack.size() -1 . I wonder if it is better to have a private member in the class to hold the size -1? I mean in turn of efficiency.
它根本不会引人注意,不要进行只会为您节省一两个处理器周期的优化,而是可以降低算法复杂性或 I/O 操作数量的优化。
Also, if we were to use ArrayList to implement this Stack. Will it run more efficiently? I mean, ArrayList has a lot of overhead such as internal call of methods.
如果您开始在内部增长数组,它将与您自己的实现运行相同。
Lastly, I know my code is not great, so please give me some advice to make it better! Thank you so much!
这对于学习项目来说非常好,继续努力 ;)
关于java - 在 Java 中使用数组实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436708/