線性表——棧
阿新 • • 發佈:2018-11-27
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(); } };