栈的实现
栈是一种先进后出的数据结构,
首先用数组实现,底层使用数组:
public class MyArrayStack<T> {
private Object[] objs = new Object[16];
private int size = 0;
public boolean isEmpty() {
return size == 0;
}
public void clear() {
// 将数组中的数据置为null, 方便GC进行回收
for (int i = 0; i < size; i++) {
objs[size] = null;
}
size = 0;
}
public int length() {
return size;
}
public boolean push(T data) {
// 判断是否需要进行数组扩容
if (size >= objs.length) {
resize();
}
objs[size++] = data;
return true;
}
/**
* 数组扩容
*/
private void resize() {
Object[] temp = new Object[objs.length * 3 / 2 + 1];
for (int i = 0; i < size; i++) {
temp[i] = objs[i];
objs[i] = null;
}
objs = temp;
}
public T pop() {
if (size == 0) {
return null;
}
return (T) objs[--size];
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("MyArrayStack: [");
for (int i = 0; i < size; i++) {
sb.append(objs[i].toString());
if (i != size - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
栈的链表实现,底层使用链表:
public class MyLinkedStack<T> {
/**
* 栈顶指针
*/
private Node top;
/**
* 栈的长度
*/
private int size;
public MyLinkedStack() {
top = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void clear() {
top = null;
size = 0;
}
public int length() {
return size;
}
public boolean push(T data) {
Node node = new Node();
node.data = data;
node.pre = top;
// 改变栈顶指针
top = node;
size++;
return true;
}
public T pop() {
if (top != null) {
Node node = top;
// 改变栈顶指针
top = top.pre;
size--;
return node.data;
}
return null;
}
/**
* 将数据封装成结点
*/
private final class Node {
private Node pre;
private T data;
}
}