目录
1. 栈的简单介绍
栈:后进先出
栈的操作:
push(E):增加一个元素E
pop():弹出元素E
peek():显示栈顶元素,但不出栈
empty():判断栈是否为空
补充:top有的地方指向栈顶元素,有的地方指向栈顶再往上的一个空单位,这个根据题目要求设计就好,本文采用指向栈顶空位。
这里简单展示一下java.util包下的栈的基本定义和用法。
Stack<Integer> stack = new Stack();
stack.push(1);
stack.push(2);
while(!stack.empty()){
//只显示,不出栈
sout.stack.peek();
//出栈并显示
sout.stack.pop();
}
2. 基于数组实现栈
每次入栈前先判断栈的容量是否够用,如果不够,可以进行扩容。
入栈过程如下所示:
出栈过程:
top先将栈顶元素取出,然后再执行top--。
class Mystack<T> {
//实现栈的数组
private Object[] stack;
//栈顶元素
private int top;
Mystack() {
//初始容量为10
stack = new Object[10];
}
//判断是否为空
public boolean isEmpty() {
return top == 0;
}
//返回栈顶元素
public T peek() {
T t = null;
if (top > 0)
t = (T) stack[top - 1];
return t;
}
public void push(T t) {
expandCapacity(top + 1);
stack[top] = t;
top++;
}
//出栈
public T pop() {
T t = peek();
if (top > 0) {
stack[top - 1] = null;
top--;
}
return t;
}
//扩大容量
public void expandCapacity(int size) {
int len = stack.length;
if (size > len) {
size = size * 3 / 2 + 1;//每次扩大50%
stack = Arrays.copyOf(stack, size);
}
}
public static void main(String[] args) {
Mystack<String> stack = new Mystack<>();
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
stack.push("java");
stack.push("is");
stack.push("beautiful");
stack.push("language");
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
}
}
3. 基于链表实现栈
插入和删除都在头结点进行就可以了。
class ListStack<T> {
//定义链表
class Node<T> {
public T t;
public Node next;
}
public Node<T> head;
//构造函数初始化头指针
ListStack() {
head = null;
}
//入栈
public void push(T t) {
if (t == null) {
throw new NullPointerException("参数不能为空");
}
if (head == null) {
head = new Node<T>();
head.t = t;
head.next = null;
} else {
Node<T> temp = head;
head = new Node<>();
head.t = t;
head.next = temp;
}
}
//出栈
public T pop() {
if (head == null) {
return null;
}
T t = head.t;
head = head.next;
return t;
}
//取栈顶元素
public T peek() {
if (head == null) {
return null;
}
T t = head.t;
return t;
}
//栈空
public boolean isEmpty() {
if (head == null)
return true;
else
return false;
}
public static void main(String[] args) {
ListStack stack = new ListStack();
System.out.println(stack.isEmpty());
stack.push("Java");
stack.push("is");
stack.push("beautiful");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
}
}