美文网首页
数据结构-栈

数据结构-栈

作者: 半个橙子 | 来源:发表于2018-11-16 10:34 被阅读0次

栈是限定仅在表尾进行插入和删除操作的线性表
允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈称为空栈。栈又称为后进先出的线性表


image.png

Java中的栈

Stack.png
Vector

Vector也是用数组实现的,相对于ArrayList,Vector是线程安全的。Vector使用synchronized 做线程同步。

    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }   
 public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * Appends the specified element to the end of this Vector.
     *
     * @param e element to be appended to this Vector
     * @return {@code true} (as specified by {@link Collection#add})
     * @since 1.2
     */
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
Stack

Stack继承Vector其中添加了自己的方法来实现入栈和出栈,还是用的父类Vector的方法来执行元素操作

public
class Stack<E> extends Vector<E> {
    public Stack() {
    }
    public E push(E item) {
        addElement(item);
        return item;
    }
    public synchronized E pop() {
        E       obj;
        int     len = size();
        obj = peek();
        removeElementAt(len - 1);
        return obj;
    }
    public synchronized E peek() {
        int     len = size();
        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }
    public boolean empty() {
        return size() == 0;
    }
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);
        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }
}

两个栈实现中缀表达式转后缀表达式并计算结果

数字输出,运算符进栈,括号匹配出栈,栈顶运算符优先级低出栈

  • 中缀表达式:10 + ( 2 + 3 ) * 5 - 10 / 2 + 2
  • 后缀表达式:10 2 3 + 5 * + 10 2 / - 1 +
  • 结果:31
package com.execlib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Stack;
import java.util.regex.Pattern;

/**
 * 测试中缀表达式转后缀表达式并计算结果
 * 中缀表达式:10 + ( 2 + 3 ) * 5 - 10 / 2 + 2
 * 后缀表达式:10 2 3 + 5 * + 10 2 / - 1 +
 * 结果:31
 */
public class TestExp {
    public static Stack<String> symbolStack = new Stack();
    private static OptStack optStack = new OptStack();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        while (true){
            System.out.println("Enter your exp:");
            str = br.readLine();
            if (str == null||str.trim()==null||str.trim()=="")
                continue;
            String pattern = "[\\ \\.0-9\\+\\-*/()]*";
            if (!Pattern.matches(pattern,str)){
                System.err.println("exp err!");
                continue;
            }
            String[] resStr = str.split(" ");
            for (int i = 0 ;i<resStr.length;i++){
                String item = resStr[i];
                if ("+".equals(item)||"-".equals(item)||"(".equals(item)){
                    symbolStack.push(item);
                }else if ("*".equals(item)||"/".equals(item)){
                    optStack.push(resStr[++i]);
                    optStack.push(item);
                    if (symbolStack.contains("-")||symbolStack.contains("+")){
                        while (symbolStack.size()!=0){
                            String peek = symbolStack.peek();
                            if ("-".equals(peek)||"+".equals(peek)){
                                optStack.push(symbolStack.pop());
                            }else {
                                break;
                            }
                        }
                    }
                }else if (")".equals(item)){
                    while (symbolStack.size()!=0){
                        String pop = symbolStack.pop();
                        if ("(".equals(pop)){
                            break;
                        }
                        optStack.push(pop);
                    }
                }else {
                    optStack.push(item);
                }
            }
            while ( symbolStack.size()!= 0){
                optStack.push(symbolStack.pop());
            }
            Object result = optStack.calculate();
            System.out.println("\nresult:"+result);
        }
    }

    /**
     * 入栈并计算
     */
    public static class OptStack extends Stack<String>{
        @Override
        public String push(String item) {
            System.out.print(item+" ");
            if (this.size()>=2){
                if ("+-*/".contains(item)){
                    BigDecimal res = new BigDecimal("0");
                    BigDecimal sec = new BigDecimal(this.pop());
                    BigDecimal fir = new BigDecimal(this.pop());
                    if ("+".equals(item)){
                        res = fir.add(sec);
                    }else if ("-".equals(item)){
                        res = fir.subtract(sec);
                    }else if ("*".equals(item)){
                        res = fir.multiply(sec);
                    }else if ("/".equals(item)){
                        res = fir.divide(sec);
                    }
                    return super.push(res.toString());
                }
            }
            return super.push(item);
        }
        public Object calculate(){
            return this.peek();
        }
    }
}

相关文章

  • 栈和队列

    1、栈 栈是一种先进先出的数据结构。栈顶进栈,栈顶出栈。 数据结构 栈的初始化 进栈 出栈 栈的最小值 2、队列 ...

  • 004 go语言实现栈

    1 数据结构 数据结构: 要实现的功能:0 栈的初始化1 获取栈长度2 入栈3 出栈4 清空栈内容5 判断栈是否为...

  • java高级知识点

    1.数据结构 程序=数据结构+算法 栈:后进先出,线性结构 入栈:push 出栈:pop假如已知入栈顺序是ab...

  • 栈和堆以及栈区和堆区的区别

    栈和堆以及栈区和堆区的区别 数据结构中的栈和堆 栈:具有先进后出性质的数据结构 堆:一种经过排序的树形数据结构,节...

  • 数据结构与算法 第二节:栈 栈: 一种先进后出的数据结构。可以想象成手枪的弹夹。 栈的特点: 栈的行为: 栈的代...

  • 2019-07-11—栈

    栈:Java数据结构和算法(四)——栈 string和char一般这么转化: 21、定义栈的数据结构,请在该类型中...

  • 什么是堆栈?

    堆与栈是两种数据结构,并不是一种数据结构,堆是堆,栈是栈。 1、栈:是一种只能在一端进行插入和删除的数据结构。 允...

  • 05--栈 递归

    栈 栈(Stack)又名堆栈,它是一种重要的数据结构。从数据结构角度看,栈也是线性表,其特殊性在于栈的基本操作是线...

  • 18-04-21 python3 算法笔记 002基本数据结构

    线性数据结构 栈,队列,deques,列表其元素在数据结构中的位置由它被添加时的顺序决定。 栈 后进先出栈 LI...

  • 数据结构

    数据结构:要写!!手动!!数据结构非常简洁才可 栈 eg. 弹栈压栈的过程 链表 就是原型链不断的连接,要断去某个...

网友评论

      本文标题:数据结构-栈

      本文链接:https://www.haomeiwen.com/subject/yzbrfqtx.html