栈具有先进后出的特性。栈和队列一样,同样是一种特殊的列表。本文将介绍栈的基本接口及数组栈、链栈的Java实现。
包含了基本的栈操作方法。
源码
public interface IStack<T> {
void push(T data); // 入栈
T peek(); // 取栈顶元素
T pop(); // 出栈
int size(); // 长度
boolean isEmpty(); // 是否为空
}
使用数组实现,需要注意的是,这里复用了count
变量,使它具有计数和栈顶指针的两个功能。
源码
测试类
public class MyArrayStack<T> implements IStack<T> {
private T[] datas;
int count = 0; // 栈长度,兼栈顶指针
int capacity; // 数组容量
public MyArrayStack(int capacity) {
this.capacity = capacity;
this.datas = (T[]) new Object[capacity];
}
@Override
public void push(T data) {
if (count == capacity)
throw new RuntimeException("栈已满");
this.datas[count++] = data;
}
@Override
public T peek() {
if (isEmpty())
throw new RuntimeException("栈为空");
return datas[count - 1];
}
@Override
public T pop() {
if (isEmpty())
throw new RuntimeException("栈为空");
return datas[--count];
}
@Override
public int size() {
return count;
}
@Override
public boolean isEmpty() {
return count == 0;
}
}
public class MyLinkedStack<T> implements IStack<T> {
private class Node {
T data;
Node next;
Node() {}
Node(T data) {
this.data = data;
}
Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
private Node top = new Node(); // 栈顶为top.next
private int count = 0;
@Override
public void push(T data) {
Node node = new Node(data, top.next);
top.next = node;
count++;
}
@Override
public T peek() {
if (isEmpty())
throw new RuntimeException("栈为空");
return top.next.data;
}
@Override
public T pop() {
if (isEmpty())
throw new RuntimeException("栈为空");
T res = top.next.data;
top = top.next;
count--;
return res;
}
@Override
public int size() {
return count;
}
@Override
public boolean isEmpty() {
return count == 0;
}
}