栈
什么是栈?
栈(stack)是个有序线性表,只能在表的一端(称为栈顶,top)执行插入和删除操作。最后插入的数据将最先删除。所以,栈也称为后进先出(Last In First Out, LIFO)或先进后出(First In Last Out, FILO)线性表。
入栈和出栈

栈的应用
- 符号匹配
- 中缀表达式转换为后缀表达式
- 计算后缀表达式
- 实现函数的调用(包括递归)
- 网页浏览器中已访问页面的历史记录(后退按钮)
- 文本编辑器中的撤销
- HTML和XML文件中的标签匹配
栈的实现
1.基于简单数组的实现方法

public class ArrayStack {
private int top;
private int capacity;
private int[] array;
public ArrayStack() {
capacity = 1;
array = new int[capacity];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1; // 或者 top == array.length
}
public void push(int data) {
if (isFull()) {
System.out.println("Stack Overflow");
} else {
array[++top] = data;
}
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is Empty");
return 0;
} else {
return array[top--];
}
}
public void delete() {
top = -1;
}
}
2.基于动态数组的实现方法
方法1实现的栈最大空间必须先声明且不能改变,所以可以jy,新建一个比原数组空间大一倍的新数组,然后复制元素到新的数组中。

public class DynArrayStack {
private int top;
private int capacity;
private int[] array;
public DynArrayStack() {
capacity = 1;
array = new int[capacity];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1; // 或者 top == array.length
}
public void doubleStack() {
int newArray[] = new int[capacity * 2];
System.arraycopy(array, 0, newArray, 0, capacity);
capacity = capacity * 2;
array = newArray;
}
public void push(int data) {
if (isFull()) {
doubleStack();
}
array[++top] = data;
}
public int pop() {
if (isEmpty()) {
throw new EmptyStackException();
} else {
return array[top--];
}
}
public void delete() {
top = -1;
}
}
3.基于链表的实现方法
使用链表实现栈。通过在链表的表头插入元素的方式实现push操作,删除链表表头实现pop操作

public class LLStack {
private LLNode headNode;
public LLStack() {
this.headNode = new LLNode(null);
}
public boolean isEmpty() {
return headNode == null;
}
public void push(int data) {
if (headNode == null) {
headNode = new LLNode(data);
} else if (headNode.getData() == null) {
headNode.setData(data);
} else {
LLNode node = new LLNode(data);
node.setNext(headNode);
headNode = node;
}
}
public int pop() {
if (headNode == null) {
throw new EmptyStackException();
} else {
int data = headNode.getData();
headNode = headNode.getNext();
return data;
}
}
public void delete() {
headNode = null;
}
}

浙公网安备 33010602011771号