首页 > 编程知识 正文

编写实现顺序栈的基本算法,顺序栈的算法实现常见问题

时间:2023-05-03 16:47:35 阅读:264427 作者:997

算法笔记–简单实现栈的先入后出(FILO,First In Last Out)功能

stack 栈,是一个 先入后出(FILO,First In Last Out)的 有序列表,可以形象地理解为手枪的弹匣,装子弹是入栈,打枪是出栈。

主要概念

栈顶(Top):允许插入和删除的一端,为 变化的一端。称为栈顶栈底(Bottom):另一端为 固定的一端,称为栈底

单向链表如图所示:

解题:栈的实现可以用数组、链表来实现

定义一个数据存储类型,栈顶指针入栈:栈顶指针++出栈:栈顶指针–

栈的优点:

子程序的调用方便:在跳往子程序前,会先将上下文信息压到堆栈中,直到子程序执行完后再将上下文信息弹出并恢复。处理递归调用二叉树的遍历图形的深度优先(depth-first)搜索法

案例实践

public class SimpleStack { public static void main(String[] args) { MyArrayStack myArrayStack = new MyArrayStack<String>(new String[100]); myArrayStack.push("hello"); myArrayStack.push("world!"); myArrayStack.push("this"); myArrayStack.push("is"); myArrayStack.push("stack"); myArrayStack.print(); System.out.println("pop a value" + myArrayStack.pop()); myArrayStack.print(); }}/** * 使用数组简单实现栈的功能 */class MyArrayStack<T> { T[] stack; // 数据存储 int maxSize; // 栈最大数量 int top = -1; // 栈顶位置 public MyArrayStack(T[] t ) { this.maxSize = t.length - 1; stack = t; } /** * 是否已满 * * @return */ public boolean isFull() { return maxSize - 1 == top; } /** * 是否为空 * * @return */ public boolean isEmpty() { return top == -1; } /** * 入栈 * * @param value */ public void push(T value) { if (isFull()) { System.out.println("栈已满"); return; } stack[++top] = value; } /** * 出栈 * * @return */ public T pop() { if (isEmpty()) { throw new RuntimeException("栈中无数据"); } return stack[top--]; } /** * 显示栈中数据,从栈顶开始显示,也就是按出栈的顺序显示 */ public void print() { if (isEmpty()) { System.out.println("栈中无数据"); return; } for (int i = top; i >= 0; i--) { System.out.println("index=" + i + " value=" + stack[i]); } }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。