package com.wrial.stack;
/*
* @Author Wrial
* @Date Created in 8:48 2019/10/10
* @Description 数组实现栈
*/
public class ArrayStackTest {
public static void main(String[] args) {
Stack<Integer> arrayStack = new ArrayStack<>();
System.out.println("栈空:" + arrayStack.isEmpty());
System.out.println("栈满" + arrayStack.isFull());
arrayStack.push(1);
arrayStack.push(2);
arrayStack.showAll();
System.out.println("______________________");
System.out.println("出栈" + arrayStack.pop());
arrayStack.showAll();
System.out.println("栈空:" + arrayStack.isEmpty());
System.out.println("栈满" + arrayStack.isFull());
}
}
interface Stack<T> {
/**
* 栈是否为空
*/
boolean isEmpty();
/**
* data元素入栈
*/
void push(T data);
/**
* 返回栈顶元素,未出栈
*/
T peek();
/**
* 出栈,返回栈顶元素,同时从栈中移除该元素
*/
T pop();
/**
* 是否栈满
*/
boolean isFull();
/**
* 遍历栈
*/
void showAll();
}
class ArrayStack<T> implements Stack {
private T[] array;
private int capacity;
private int top = -1; //栈顶初始化为-1
ArrayStack(int capacity) {
this.capacity = capacity;
array = (T[]) new Object[capacity];
}
ArrayStack() {
this.capacity = 16;
array = (T[]) new Object[16];
}
@Override
public boolean isEmpty() {
return top == -1;
}
@Override
public void push(Object data) {
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
array[top] = (T) data;
System.out.println("入栈成功" + array[top]);
}
@Override
public Object peek() {
return array[top];
}
public T pop() {
if (isEmpty()) {
System.out.println("栈空");
return null;
} else {
T value = array[top];
top--;
return value;
}
}
@Override
public boolean isFull() {
return top == capacity;
}
//记得遍历栈的时候是从上往下遍历
@Override
public void showAll() {
for (int i = top; i >= 0; i--) {
System.out.printf("%d\t", array[i]);
}
}
}
回顾数据结构(Java版)——实现一个间的的数组栈
最新推荐文章于 2024-07-15 08:00:00 发布