在java 的 数据结构库里是有包括这些基础的数据结构的封装,可以直接调用的 本类型的博客主要用来理解
以下是博主自己敲栈的实现,如有理解偏差,请指教 一起交流进步
具体有注释
/**
* Created by gy on 2017/8/23.
* email : guoyang000111@163.com
* 实现栈
*/
public class StackAll {
private Object array[];
private int max =10;
private int top =0;
public StackAll(){
array=new Object[max];
top=0;
}
public StackAll(int max){
this.max=max;
array=new Object[max];
top=0;
}
/**
* 给栈里塞值
* @param value
*/
public void push(Object value){
if(isFull()){
System.out.println("栈已满!");
resize(max+10);
}
array[top++]=value;
}
/**
* 取栈值
* @return
*/
public Object pop(){
if(isEmpty()){
System.out.println("栈已经空了!");
return 0;
}else{
return array[--top];
}
}
/**
* 栈满了自动增大
* @param max
*/
private void resize(int max) {
Object[] temp = new Object[max];
for(int i = 0;i<array.length;i++){
temp[i] = array[i];
}
array = temp;
}
public void clear(){
array=null;
top=0;
max=0;
}
/**
* 栈是否已满
* @return
*/
public boolean isFull(){
if(max==top){
return true;
}
return false;
}
/**
* 栈是否空
* @return
*/
public boolean isEmpty(){
if(top==0){
return true;
}
return false;
}
public static void main(String[] args) {
StackAll stack =new StackAll(10);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
}
}