/**
* 栈: 后进先出
* @author Administrator
*
*/
public class Stack {
private int[] x; //null
private int top; //0
public final int INIT_CAPACITY = 10; //用常量来标识数组初始化大小
/**
* 初始化成员
*/
public Stack(){
x = new int[INIT_CAPACITY]; //元素都是 0
}
/**
* 指定容量来创建栈
*/
public Stack(int initSize){
x = new int[initSize]; //元素都是 0
}
/**
* 清空 栈
*/
public void clear(){
x = new int[INIT_CAPACITY];
top = 0;
System.gc();//垃圾回收器回收
}
/**
* 入栈
*/
public void push(int value){
//1、首先判断栈是否已满,
if(top == x.length){
x = enlarge(x); //2、满了就要扩栈
}
//3、将value存入栈顶
x[top] = value;
//将 top ++
top++;
}
private int[] enlarge(int[] x) {
// TODO 2、满了就要扩栈,数组的长度不可变化
//2.1 所以要新建一个数组,其长度是原数组的两倍 ,且元素全是0
int[] y = new int[x.length*2];
//2.2 将 x 数组中的值复制到新数组中
System.arraycopy(x, 0, y, 0, x.length);
//2.3 j将新数组的引用地址赋值给 x ,这样 x 就指向 新数组 了
return y;
}
/**
* 出栈操作
* 将栈顶元素取出
*/
public int pop(){
//1、首先 要 判断栈是否已经是 空
if(top == 0){
throw new RuntimeException("这是一个空栈"); //已空,抛出异常
}
//2、不为空 ,则取出栈顶元素,返回
//3、top--
int result = x[--top];
return result;
}
/**
* 查看栈顶元素
*/
public int peek(){
if(x==null || x.length == 0){
throw new RuntimeException("栈的数据异常");
}
return x[top];
}
/**
* 查看栈的真实大小
*/
public int size(){
return top<=0?0:top;
}
/**
* 查看栈的容量
*/
public int getCapacity(){
return x != null? x.length:0;
}
}
* 栈: 后进先出
* @author Administrator
*
*/
public class Stack {
private int[] x; //null
private int top; //0
public final int INIT_CAPACITY = 10; //用常量来标识数组初始化大小
/**
* 初始化成员
*/
public Stack(){
x = new int[INIT_CAPACITY]; //元素都是 0
}
/**
* 指定容量来创建栈
*/
public Stack(int initSize){
x = new int[initSize]; //元素都是 0
}
/**
* 清空 栈
*/
public void clear(){
x = new int[INIT_CAPACITY];
top = 0;
System.gc();//垃圾回收器回收
}
/**
* 入栈
*/
public void push(int value){
//1、首先判断栈是否已满,
if(top == x.length){
x = enlarge(x); //2、满了就要扩栈
}
//3、将value存入栈顶
x[top] = value;
//将 top ++
top++;
}
private int[] enlarge(int[] x) {
// TODO 2、满了就要扩栈,数组的长度不可变化
//2.1 所以要新建一个数组,其长度是原数组的两倍 ,且元素全是0
int[] y = new int[x.length*2];
//2.2 将 x 数组中的值复制到新数组中
System.arraycopy(x, 0, y, 0, x.length);
//2.3 j将新数组的引用地址赋值给 x ,这样 x 就指向 新数组 了
return y;
}
/**
* 出栈操作
* 将栈顶元素取出
*/
public int pop(){
//1、首先 要 判断栈是否已经是 空
if(top == 0){
throw new RuntimeException("这是一个空栈"); //已空,抛出异常
}
//2、不为空 ,则取出栈顶元素,返回
//3、top--
int result = x[--top];
return result;
}
/**
* 查看栈顶元素
*/
public int peek(){
if(x==null || x.length == 0){
throw new RuntimeException("栈的数据异常");
}
return x[top];
}
/**
* 查看栈的真实大小
*/
public int size(){
return top<=0?0:top;
}
/**
* 查看栈的容量
*/
public int getCapacity(){
return x != null? x.length:0;
}
}