package com.handy.ds;
public class SimpleStack {
// 栈数组
private int[] arrays;
// 栈的容量
private int capacity;
// 栈元素个数
private int size;
//自动增长大小
private int autoSize=5;
public SimpleStack(int capacity) {
size = 0;
this.capacity=capacity;
arrays = new int[capacity];
}
/**
* @return the arrays
*/
public int[] getArrays() {
return arrays;
}
/**
* @param arrays
* the arrays to set
*/
public void setArrays(int[] arrays) {
this.arrays = arrays;
}
/**
* @return the capacity
*/
public int getCapacity() {
return capacity;
}
/**
* @param capacity
* the capacity to set
*/
public void setCapacity(int capacity) {
this.capacity = capacity;
}
/**
* @return the size
*/
public int getSize() {
return size;
}
/**
* @param size
* the size to set
*/
public void setSize(int size) {
this.size = size;
}
//增长函数
public void extend(int increment){
int[] extendStack=new int[capacity+increment];
capacity=capacity+increment;
for(int i=0;i<size;i++)
extendStack[i]=arrays[i];
arrays=extendStack;
}
// 出栈,返回栈顶元素,改变栈的状态
public int pop() {
if (isEmpty() == true)
return -1;
else
return arrays[--size];
}
// 进栈
public void push(int number) {
if (isFull() == true){
System.out.println("栈已经满啦!");
// capacity=capacity+autoSize;
// arrays=new int[capacity];
extend( autoSize);
System.out.println("自动增长!"+"大小:"+autoSize);
arrays[size++] = number;
}
else
arrays[size++] = number;
}
// 判断栈是否为空
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
// 判断栈是否满
public boolean isFull() {
if (size == capacity)
return true;
else
return false;
}
// 取栈顶元素,但不改变栈的状态
public int stackTop() {
if (isEmpty() == false)
return arrays[size - 1];
else
return -1;
}
}
Java简单栈的实现
最新推荐文章于 2022-01-20 18:04:21 发布