线性表——栈

1、栈的定义

  • 栈(stack)是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈的顶(top)。对栈的基本操作有Push(进栈)和Pop(出栈),前者相当于插入,后者则是删除最后面插入的元素。
  • 栈有时又叫LIFO(后进先出)表。

2、栈的实现

两种流形的实现方式:指针(链表)和数组。

3、C++ STL 栈的用法

  • 头文件
#include<stack>
  • 定义方式
stack<int>  s;//参数也是数据类型
  • 常用操作
s.empty()//如果栈为空返回true,否则返回false  
s.size()//返回栈中元素的个数  
s.pop()//删除栈顶元素但不返回其值  
s.top()//返回栈顶的元素,但不删除该元素  
s.push(X)//在栈顶压入新元素 ,参数X为要压入的元素
  • 例子
#include <iostream>
#include <stack>
using namespace std;
int main()
{
    stack<char> s;
    s.push('a');
    cout << s.top() <<endl;
    s.push('b');
    cout << s.top()<<endl;
    s.pop();
    cout << s.top()<<endl;
}

4、leetcode——逆波兰表达式求值

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> stn;
        for (auto s : tokens) {
            if (s.size() > 1 || isdigit(s[0])) {
                stn.push(stoi(s));
            }  else {
                auto x2 = stn.top(); stn.pop();
                auto x1 = stn.top(); stn.pop();
                switch (s[0]) {
                    case '+': x1 += x2; break;
                    case '-': x1 -= x2; break;
                    case '*': x1 *= x2; break;
                    case '/': x1 /= x2; break;
                }
                stn.push(x1);
            }
        }
        return stn.top();
    }
};

猜你喜欢

转载自blog.csdn.net/qq_18644873/article/details/84024115