介绍:

  1)先入后出

  2)插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,叫栈顶;另一端叫栈底。

  3)先放入元素在栈底,后放入元素在栈顶。

应用场景:

  1)子程序的调用:在跳子程序前,会先将下个指令的地址存到堆栈中,直到子程序执行完后再将地址取出,一回到原来的程序。

  2)处理递归调用:和子程序的调用类似,出了储存下一个指令的地址外,也将参数、区域变量等数据存入堆栈中。

  3)表达式的转换【中缀表达式转后缀表达式】与求值(实际解决)。

  4)二叉树的遍历。

  5)图的深度优先算法(dfs——depth first search)。

代码实现

  数组模拟栈:

public class ArrayStack {
    private int maxSize;
    private int top = -1;
    private int[] stack;

    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 data) {
        if (isFull()) {
            System.out.println("栈满,无法入栈");
            return;
        }
        top ++;
        stack[top] = data;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,无数据");
        }
        int value = stack[top];
        top --;
        return value;
    }

    public void list() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,无数据");
        }
        for (int i = top; i >= 0; i --) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
}
View Code

  链表模拟栈:

public class SingleLinkedListStack {
    private Node bootom = new Node(-1);

    public void push(int data) {
        Node newNode = new Node(data);
        Node temp = bootom;
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = newNode;
    }

    public Node pop() {
        if (bootom.next == null) {
            throw new RuntimeException("栈空");
        }
        Node temp = bootom;
        while (true) {
            Node top = temp.next;
            if (top.next == null) {
                temp.next = null;
                return top;
            }
            temp = temp.next;
        }
    }


}
class Node{
    public int no;
    public Node next;
    public Node(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                ", node=" + next +
                '}';
    }
}
View Code

 

posted @ 2021-08-31 10:08  墨梅青莲  阅读(35)  评论(0)    收藏  举报