目录
01 堆栈应用场景介绍
02 什么是堆栈(Stack)
堆栈(Stack):具有一定操作约束的线性表
- 只在一端(栈顶,Top)做插入、删除
- 插入数据:入栈(Push)
- 删除数据:出栈(Pop)
- 后入先出:Last In First Out(LIFO)
2.1 堆栈的抽象数据类型描述
-
类型名称:堆栈(Stack)
-
数据对象集:一个有 0 个或多个元素的有穷线性表
-
操作集:长度为 MaxSize 的堆栈 S ∈ Stack,堆栈元素 item ∈ ElementType
堆栈的基本操作主要有:
2.2 栈的思路分析和代码实现
思路分析(使用数组模拟栈)
- 使用数组来模拟栈
- 定义一个top来表示栈顶,初始化为-1
- 当有数据data加入到栈时(push): top++,stack[top] = data;
- 出栈(pop)操作,int value = stack[top]; top-- ; return value;
2.2.1 数组实现栈
class ArrayStack{
private int maxSize; // 定义栈的大小
private int[] stack; // 数组模拟栈,栈中数据放在此数组中
private int top = -1; // top表示栈顶,初始化为-1
public ArrayStack(int maxSize) { // 构造器用于初始化栈
this.maxSize = maxSize;
this.stack = new int[maxSize];
}
// 判断栈满
public boolean isFull(){
return top == maxSize - 1;
}
// 判断栈空
public boolean isEmpty(){
return top == -1;
}
// 入栈操作
public void push(int value){
// 先判断栈是否满
if(isFull()){
System.out.println("栈满,不能添加");
return;
}
top++;
stack[top] = value;
}
// 出栈操作: 返回栈顶数据,并重新设置栈顶
public int pop() throws Exception {
if(isEmpty()){
System.out.println("栈空,无法出栈");
throw new Exception("栈空,不饿能出栈");
}
int value = stack[top];
top--;
return value;
}
// 遍历栈,需要从栈顶开始遍历
public void list(){
if(isEmpty()){
System.out.println("栈为空");
return;
}
// 从栈顶显示数据
for(int i = top ; i >= 0; i-- ){
System.out.println(stack[i]);
}
}
测试
public class Stack {
public static void main(String[] args) throws Exception {
ArrayStack arrayStack = new ArrayStack(4);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.list();
arrayStack.pop();
System.out.println("**********");
arrayStack.list();
arrayStack.push(4);
arrayStack.push(5);
System.out.println("**********");
arrayStack.list();
arrayStack.push(6);
}
}
2.2.2 单向链表实现栈
class Stack2{
private int maxSize;
private Node top;
public Stack2(int maxSize) { //初始化栈顶
this.maxSize = maxSize;
top = null;
}
public boolean isFull(){
int i = 1;
Node temp = top;
while(temp != null){
temp = temp.next;
i++;
}
return i == maxSize;
}
public boolean isEmpty(){
return top == null;
}
public void push(Node newNode){
if(isFull()){
System.out.println("栈满不能添加");
return;
}
newNode.next = top;
top = newNode;
}
public Node pop() throws Exception {
if(isEmpty()){
throw new Exception("栈空");
}
Node node = top;
top = top.next;
return node;
}
public void list(){
if(isEmpty()){
System.out.println("堆栈空");
}
Node temp = top;
while(temp != null){
System.out.println(temp.no);
temp = temp.next;
}
}
}
class Node{
public int no;
public Node next;
public Node(int no) {
this.no = no;
}
}
测试
public class LinkedStack {
public static void main(String[] args){
Stack2 stack = new Stack2(4);
stack.list();
stack.push(new Node(1));
stack.push(new Node(2));
stack.push(new Node(3));
stack.push(new Node(4));
stack.list();
stack.push(new Node(5));
}
}