数据结构——栈(Stacks)

时间:2023-04-30 17:40:38

栈遵循LIFO ( last in first out) 即后入先出原则

栈结构类似于叠盘子 后叠上去的要先拿走 才能拿到下面的盘子

因此stack是一种访问受限的线性存储结构

用单向链表的结构来存储

stack类

 class stack
{
stack();
bool empty() const;
void pop(); //移除栈顶元素
void push()(const T&item);//增加元素至栈顶
int size() const;
T &top() const;//返回栈顶元素
}

栈的两个常见应用:

&&Run-time Stack  运行时间栈

顺序执行活动,运行栈顶的活动,运行完毕弹出。

&&RPN or Postfix Notation

将中缀表达式转化为后缀表达式压入栈中,顺序弹出进行运算。

如:a*b+c  -> ab*c+

  a*(b+c)  -> abc+*

  a-(b-(c-d))  -> abcd---

压入栈中时分为 数字栈 和 符号栈

符号栈:进栈与栈顶元素比较优先级。

    同级则先弹出栈顶元素再新元素进栈,

    优先级低则先弹出栈顶元素再与新的栈顶元素比较,

    优先级高则直接入栈。

    ‘(’ 直接入栈,碰到 ‘)’ 则将直至 ‘(’ 的符号全部弹出。

举例:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgoAAAFJCAIAAAB1h5JdAAAbJElEQVR4nO3dP3biPhfGcZ+TDWQp1NkD28jJIlKwAArq2QD9FOmoaafNSUWZLjvwW/D+HGNfycKS7Efo+ynmZIwxV1d/rnAS0rQAAIw0awcAAFBEeQAAGCgPAAAD5QEAYKA8AAAMlAcAgIHyAAAwUB4AAAbKA2q32WwaVZvNZu30rINOUUB5QO2aRncWKMeWlXLDlWNLq5Z2Ai7Ks105tqyUG64cW1q1tBNwUZ7tyrFlpdxw5djSqqWdgIvybFeOLSvlhivHllYt7QRclGe7cmxZKTdcOba0amkn4KI825Vjy0q54cqxpVVLOwEX5dmuHFtWyg1Xji2tWtoJuCjPduXYslJuuHJsadXSTsBFebYrx5aVcsOVY0urlnYCLsqzXTm2rJQbrhxbWrW0E3BRnu3KsWWl3HDl2NKqpZ2Ai/JsV44tK+WGK8eWVi3tBFyUZ7tybFkpN1w5trRqaSfgoj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