栈(Stack)

一,概念

  • 一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则
  • 栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶
  • 栈的删除操作叫做出栈。出数据在栈顶

二,栈的操作

 代码示例:
 

public class MyStack {

    public static void main(String[] args) {
        Stack s = new Stack();

        //入栈
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        s.push(5);
        s.push(6);

        //获取栈顶元素                   (栈中元素遵循后进先出,因此元素为:1,2,3,4,5,6)
        System.out.println(s.peek());

        //获取有效元素的个数                 (一共有六个元素,因此为;6)
        System.out.println(s.size());

        //出栈(获取并取出)                  (出栈并检测栈顶元素和栈中元素的个数)
        System.out.println(s.pop());         //      6
        System.out.println(s.pop());         //      5
        System.out.println(s.pop());         //      4
        System.out.println(s.pop());         //      3
        System.out.println(s.peek());        //      2
        System.out.println(s.size());        //      2
        //判断栈里面是否为空
        if(!s.empty()){
            System.out.println("栈不为空!");
        }else {
            System.out.println("栈为空!");
        }
        System.out.println(s.pop());
        System.out.println(s.pop());

        if(!s.empty()){
            System.out.println("栈不为空!");
        }else {
            System.out.println("栈为空!");
        }
    }
}

运行结果:

 

三,栈的应用实例

逆序打印链表

思路:可以借用栈的特性“后进先出”,后入栈的先出去

public void print(ListNode head){
        if(head == null){
            System.out.println("链表为空!");
        }
        ListNode cur = head;
        Stack s = new Stack();
        while(cur != null){
            s.push(cur.val);
            cur = cur.next;
        }
        while(!s.empty()){
            System.out.print(s.pop() + " ");
        }
        System.out.println();
    }

 在剑指刷题中,有两种做法,普通数组逆序,和利用栈的逆序

四,栈的模拟实现

public static class Stack<E> {
        E[] array;
        int size;   // 用来表示栈中总共有多少个元素 || size-1表示栈顶元素的位置
        public Stack(){
            array = (E[])new Object[3];
            size = 0;
        }

        public void push(E e){
            // 1. 先确保栈中空间足够
            ensureCapacity();

            // 2. 插入元素
            array[size] = e;
            size++;
        }

        public E pop(){
            E ret = peek();
            size--;
            return ret;
        }

        public E peek(){
            if(empty()){
                throw new RuntimeException("pop: 栈是空的");
            }

            return array[size-1];
        }

        public boolean empty(){
            return 0 == size;
        }

        public int size(){
            return size;
        }

        private void ensureCapacity(){
            if(size == array.length){
                int newCapacity = size*2;
                array = Arrays.copyOf(array, newCapacity);
            }
        }

        public static void main(String[] args) {
            Stack<String> s = new Stack<>();
            s.push("11");
            s.push("22");
            s.push("33");
            s.push("44");
            s.push("55");
            s.push("66");
            s.push("77");
            System.out.println(s.size());
            System.out.println(s.peek());

            s.pop();
            s.pop();
            System.out.println(s.size());
            System.out.println(s.peek());
        }
    }

 

五,栈,虚拟机栈,栈帧的区别

栈:一般认为时一种数据结构,它继承了vector,在java集合中实现了Stack,也是线程安全的

虚拟机栈: 具有特殊作用的一块内存,jvm为了更好的管理数据,将内存按照不同的需求划分出来的一种结构(堆区,栈区)

栈区是线程私有的,存放的是一些有关于函数调用的信息,主要是栈帧,如果栈区内存不够时,会抛出StackoverflowException的异常,当中的元素(栈帧)是按照数据结构中栈的特性来实现的

 栈帧:一种与函数调用有关的结构,如,局部变量,操作数栈。每个方法在调用时,jvm都会创建一个栈帧,将栈帧压入到虚拟机栈中,当方法调用结束时,对应的栈帧就会从虚拟机栈中出栈 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题非常适合用程序解决。以下是用stack实现简单计算器的c代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define STACKLEN 1000 /* 的最大容量 */ typedef struct { int top; /* 顶指针 */ double data[STACKLEN]; /* 元素数组 */ } Stack; void push(Stack *pstack, double value) { if (pstack->top == STACKLEN - 1) { printf("Error: stack overflow!\n"); exit(EXIT_FAILURE); } else { pstack->data[++pstack->top] = value; } } double pop(Stack *pstack) { if (pstack->top == -1) { printf("Error: stack underflow!\n"); exit(EXIT_FAILURE); } else { return pstack->data[pstack->top--]; } } bool is_digit(char c) { return (c >= '0' && c <= '9'); } int precedence(char op) { if (op == '+' || op == '-') return 1; else if (op == '*' || op == '/') return 2; else return 0; } double calculate(double left, char op, double right) { switch (op) { case '+': return left + right; case '-': return left - right; case '*': return left * right; case '/': return left / right; default: printf("Error: invalid operator!\n"); exit(EXIT_FAILURE); } } double eval(char *expr) { Stack operandStack; operandStack.top = -1; Stack operatorStack; operatorStack.top = -1; int len = strlen(expr); int i = 0; while (i < len) { char c = expr[i]; if (is_digit(c)) { double value = 0.0; while (i < len && is_digit(expr[i])) { value = value * 10.0 + (double)(expr[i] - '0'); i++; } push(&operandStack, value); } else { while (operatorStack.top != -1 && precedence(operatorStack.data[operatorStack.top]) >= precedence(c)) { char op = operatorStack.data[operatorStack.top--]; double right = pop(&operandStack); double left = pop(&operandStack); push(&operandStack, calculate(left, op, right)); } push(&operatorStack, c); i++; } } while (operatorStack.top != -1) { char op = operatorStack.data[operatorStack.top--]; double right = pop(&operandStack); double left = pop(&operandStack); push(&operandStack, calculate(left, op, right)); } return pop(&operandStack); } int main() { char s[1000]; printf("Please enter an expression: "); scanf("%s", s); double result = eval(s); printf("Result: %f\n", result); return 0; } ``` 这段代码定义了两个:一个操作数(operandStack)和一个操作符(operatorStack),通过不断入和出的操作,实现对表达式进行求值。其中,is_digit函数用于判断一个字符是否是数字;precedence函数用于比较两个运算符的优先级;calculate函数用于计算两个操作数和一个操作符的运算结果;eval函数是主函数,用于将输入的表达式转化为数字计算结果。 希望这个回答能够帮助您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值