【发布时间】:2017-12-21 22:17:54
【问题描述】:
在 Java 中,我可以像下面那样实现我自己的 Stack 或使用已经提供的 java.util.Stack 类。
public class stack {
private int maxSize; //max size of stack
private char[] stackArray;
private int top; //index poistion of last element
public stack(int size){
this.maxSize=size;
this.stackArray=new char[maxSize];
this.top=-1; //
}
public void push(char j){
if (isFull()) {
System.out.println("SORRY I CANT PUSH MORE");
}else{
top++;
stackArray[top]=j;
}
}
public char pop(){
if(isEmpty()){
System.out.println("Sorry I cant pop more!");
return '0';
}else{
int oldTop=top;
top--;
return stackArray[oldTop];
}
}
public char peek(){
if(!isEmpty()) {
return stackArray[top];
}
}
public boolean isEmpty(){
return (top==-1);
}
public boolean isFull(){
return (maxSize-1 == top);
}
} //end of stack class
第二种方法是使用Java API中的Stack类。
Stack<String> stacky = new Stack<>();
Java 中Queues 的情况也是如此。
在使用Stacks 或Queues 时,我应该使用自己的实现吗?
【问题讨论】:
标签: java data-structures stack queue