以前看到有人说程序员的三大基本功:程序逻辑,数据结构和sql语句。
闲暇之余,突然想起栈,队列和链表的数据结构,对于他们的底层实现已经很久没接触了,就准备手写一下感受感受。
栈结构就是实现了先进后出,浏览器的退回,函数调用栈都是这样的结构,如下就是栈的简单实现:
/**
* 栈
* 基于数组
*
* @author zeng wenbin
* @date Created in 2019/10/6
*/
public class MyStack<D> {
/**
* 数据数组
*/
private D[] ds;
/**
* 栈顶脚标
*/
private int index = -1;
public MyStack(D[] ds){
this.ds = ds;
}
public void push(D d){
if (isFull()){
throw new IndexOutOfBoundsException("栈已满,无法压入!");
}
ds[++index] = d;
}
/**
* 是否满栈
*
* @return 布尔
*/
public Boolean isFull(){
return index == (ds.length-1);
}
/**
* 获取栈大小
*
* @return 栈大小
*/
public int size(){
return index + 1;
}
/**
* 获取栈顶元素,不删除
*
* @return 栈顶元素
*/
public D peek(){
if (index == -1){
throw new RuntimeException("空栈无法获取数据!");
}
return ds[index];
}
/**
* 获取栈顶元素并删除
* @return 栈顶元素
*/
public D pop(){
if (index == -1){
throw new RuntimeException("空栈无法获取数据!");
}
D d = ds[index];
ds[index--] = null;
return d;
}
/**
* 获取栈数组
*
* @return 栈数组
*/
public D[] getArray(){
return ds;
}
}
很简单的实现方式,没什么难度。
接下来是队列,队列的目的是先进先出,我这里使用了链表去做实现,当然也可以用循环数组的方式去实现,代码如下:
/**
* 队列
* 基于链表
*
* @author zeng wenbin
* @date Created in 2019/10/6
*/
public class MyQueue<D> {
/**
* 队列数据链表
*/
private List<D> ds = new LinkedList<>();
/**
* 队列最大数量
*/
private Integer maxCount;
public MyQueue(Integer maxCount