package com.yy.stack;
public class Stack {
//数组实现栈结构
private Object[] obj;
//栈的长度
private int index;
/**
* 初始化长度为10的栈
*/
public Stack() {
obj = new Object[10];
}
/**
* 初始化长度为length的栈
* @param length
*/
public Stack(int length){
obj = new Object[length];
}
/**
* 进栈
*/
public void push(Object o){
expandStack();
obj[index++] = o;
}
/**
* 出栈
*/
public void pop(){
//1.先判断数组是否为空
//2.出栈
if(isEmpty()){
System.out.println("栈为空");
}else{
Object[] temp = new Object[index--];
System.arraycopy(obj, 0, temp, 0, index);
obj = temp;
}
}
/**
* 出栈并返回数据
* @return
*/
public Object getPop(){
Object o = null;
if(isEmpty()){
System.out.println("栈为空");
}else{
o = getLast();
Object[] temp = new Object[index--];
System.arraycopy(obj, 0, temp, 0, index);
obj = temp;
}
return o;
}
/**
* 获取栈的最后一位数据
* @return
*/
public Object getLast() {
int length = index;
return obj[--length];
}
/**
* 判断是否为空栈
* @return
*/
public boolean isEmpty() {
if(index == 0){
return true;
}
return false;
}
/**
*
* 判断栈的容量并扩大
*/
private void expandStack() {
//判断当前栈的长度是否满了
if(index >= obj.length){
Object[] temp = new Object[obj.length * 2];
System.arraycopy(obj, 0, temp, 0, obj.length);//数组拷贝
obj = temp;
}
}
/**
* 获取栈的长度
* @return
*/
public int getSize(){
return index;
}
/**
* 打印栈
*/
public void printStack(){
for(int i = 0; i < index; i++){
System.out.println(obj[i]);
}
}
public static void main(String[] args) {
Stack s = new Stack();
int i = 1;
int j = 2;
s.push(i);
s.push(j);
System.out.println(s.getPop());
s.printStack();
}
}
简单栈的数组实现
最新推荐文章于 2021-10-20 23:35:34 发布