栈是仅限于在表尾进行插入和删除的线性表,它遵循后进先出原则
代码实现部分
package Stack;
public interface Stack_i <T>{
//入栈
void push(T e);
//出栈
T pop();
//获取栈顶元素
T peek();
//获取栈的元素个数
int size();
//栈是否为空
boolean isEmpty();
}
package Arrays;
import java.util.Random;
public class MyArr<T> {
private int capacity = 0;
private int size = 0;
private T[] arr;
public MyArr(int capacity) {
if (capacity < 0) this.capacity = 10; //if no right input, we will initial capacity 10
this.capacity = capacity;
this.arr = (T[]) new Object[capacity];
}
public int getCapacity() {
return capacity;
}
public int getSize() {
return size;
}
public T[] setCapacity(int capacity) {
if (capacity < 0) {
throw new RuntimeException("扩大小异常");
}
this.capacity = capacity;
T[] newNum = (T[]) new Object[capacity];
for (int i = 0; i < this.size; ++i) {
newNum[i] = this.arr[i];
}
return newNum;
}
//增加元素
public void add(T val) {
if (this.size >= this.capacity) {
this.arr = setCapacity(2 * this.capacity);
}
this.arr[this.size++] = val;
}
//数组末尾增加元素
public void addLst(T val){
this.add(val);
}
//删除元素
public T removeByIndex(int index) {
if (index < 0 || index > this.capacity) {
throw new RuntimeException("数组越界");
}
for (int i = index; i < size - 1; ++i) {
arr[i] = arr[i + 1];
}
size--;
if (size < this.capacity / 4 && this.capacity > 4) {
arr = setCapacity(this.capacity / 4);
}
return this.arr[index];
}
//删除数组末尾元素
public T removeLast(){
return this.removeByIndex(this.size-1);
}
//修改位置元素
public void modify(int index, T val) {
if (index < 0 || index > size - 1) {
throw new RuntimeException("数组越界");
}
arr[index] = val;
}
//获取某元素位置
public int locateVal(T val) {
for (int i = 0; i < size; ++i) {
if (arr[i] == val) {
return i;//return index
}
}
// if no find return -1
return -1;
}
//获取尾元素
public T getLast(){
return this.arr[this.size-1];
}
//打印元素
@Override
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append('[');
for (int i = 0; i < this.size - 1; ++i) {
stringBuffer.append(arr[i] + ",");
}
if(size>0) stringBuffer.append(arr[size - 1]);
stringBuffer.append(']');
return stringBuffer.toString();
}
}
import Arrays.MyArr;
public class StackImplement<T> implements Stack_i<T>{
private MyArr<T> data;
private int size=0;
@Override
public void push(T e) {
this.size++;
this.data.addLst(e);
}
public StackImplement() {
data = new MyArr<>(10);
}
@Override
public T pop() {
if(this.isEmpty()){
throw new RuntimeException("栈为空");
}
return this.data.removeLast();
}
@Override
public T peek() {
return this.data.getLast();
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
if(size==0)return true;
return false;
}
public int getCapacity(){
return this.data.getCapacity();
}
}