- 为自己做记录,昨天因为忙的缘故也没有发表(坚持,一天理解一个小知识点,小白打卡第二天)
- 今天分享数据结构中的 ======栈
(1)栈与系统栈
从计算机科学的角度来看,栈指的是一种数据结构,是一种先进后出的数据表。栈的最常见操作有两种:压栈(PUSH)、弹栈(POP);
用于标识栈的属性也有两个:栈顶(TOP)、栈底(BASE)。
栈在内存中的存放是高地址是栈底(Base),低地址是栈顶(Top)。
(在这里关于内存地址的咱不说明,涉及太多了,先演示实现)
(2)代码实现
一、定义的栈
/**
* @ClassName: Stack
* @Author: Clement
* @Date: 2019/8/22 08:21
* @Version: 1.0
* @Description:
*/
public class Stack<T> {
/**
* 数组最大下标
*/
private int index;
private int top;
private Object[] data;
public Stack(){}
public Stack(int capacity){
this.index=capacity-1;
data = new Object[capacity];
top = -1;
}
/**
* 压栈 数据存入数组栈顶指针下标+1后对应的位置
* 确保top总是指向栈顶位置 top的初始值为-1 每次入栈top先递增1
* 则top代表定义的数组下标已经有值
* 每次入栈作比较 如果top的值等于数组最大下标,
* 则代表数组最大下标已经有值,则栈满不能入栈
* @param t
*/
public synchronized void push(T t) {
if(this.top>=this.index) {
System.out.println("栈满");
return;
}
data[++top] = t;
}
/**
* 出栈 从栈顶指针指向的元素开始出栈
* 实现先进后出。
* @return
*/
public synchronized T pop(){
if(top < 0){
System.out.println("空栈");
return null;
}
@SuppressWarnings("unchecked")
T t = (T) data[top--];
return t;
}
/**
* 获得栈顶元素
* top的值和数组下标所对应 所以data[top]取的是最后入栈的值 也就是栈顶的值
* @return
*/
public T peek(){
if(top < 0){
System.out.println("空栈");
return null;
}
return (T)data[top];
}
/**
* 获取栈的长度
* top和数组下标所对应 所以取长度top+1
* @return
*/
public int getLength(){
return top <=0 ? 0:top+1;
}
/**
* 判断是否为空 空返回false,否则返回true
* @return
*/
public boolean isEmpty() {
return top<0?false:true;
}
/**
* 返回对象到栈顶的位置
* @param o
* @return
*/
public synchronized int search(Object o) {
int i = lastIndexOf(o);
//如果i>0,则说明为i的坐标下符合查询的值,则top的值等于最大下标 top-i就是元素到栈顶的位置
if (i >= 0) {
return top - i;
}
//如果未找到,返回负一
return -1;
}
public synchronized int lastIndexOf(Object o) {
return lastIndexOf(o, this.top);
}
public synchronized int lastIndexOf(Object o, int top) {
//判断栈顶元素的下标是否超过了定义数组的长度
if (top>this.index){
throw new IndexOutOfBoundsException(top + " >= "+this.index);
}
//判断是否为null值的元素
if (o == null) {
/*
如:数组定义长度为5 入栈值:1,2,3,null,5
则最后入栈后top等于4,比对完毕后返回当前所在的i值,即坐标值
*/
for (int i = top; i > 0; i--) {
if (data[i]==null){
return i;
}
}
} else {
for (int i = top; i > 0; i--){
if (o.equals(data[i])) {
return i;
}
}
}
return -1;
}
}
测试:
import org.junit.Test;
/**
* @ClassName: StackTest
* @Author: Clement
* @Date: 2019/8/22 08:43
* @Version: 1.0
* @Description:
*/
public class StackTest {
@Test
public void test1() {
Stack<Integer> s = new Stack<Integer>(4);
s.push(1);
s.push(null);
s.push(3);
s.push(null);
s.pop();
int distance = s.search(3);
System.out.println("3 距离栈顶的距离:"+distance);
s.push(4);
s.push(5);
System.out.println("栈的长度:"+s.getLength());
for(int i=0;i<5;i++) {
s.pop();
}
}
}
运行结果: