1.栈是一种典型的数据存储结构,存储中有先进后出的特点,下面看看栈的基本操作
#include<iostream>
#include<vector>
using namespace std;
typedef struct stack
{
vector<int>data;
}stack;
void push(int n,stack &root)
{
root.data.push_back(n);
}
void pop(stack& root)
{
root.data.pop_back();
}
bool empty(stack& root)
{
return root.data.size() == 0;
}
2.顺序栈的应用:进制转换
【问题描述】请用“顺序栈”解决进制转换问题,请注意:不采用顺序栈,不给分。
【输入形式】十进制数据和待转换的进制
【输出形式】转换后的数据
【样例输入1】1348 8
【样例输出1】2504
【样例输入2】2608 16
【样例输出2】A30
#include <iostream>
#include <vector>
using namespace std;
typedef vector<char> MyStack;
void push(char c, MyStack& root)
{
root.push_back(c);
}
void pop(MyStack& root)
{
if (!root.empty())
root.pop_back();
}
char top(MyStack& root)
{
if (!root.empty())
return root.back();
return '\0';
}
bool empty(MyStack& root)
{
return root.empty();
}
void judge(int num, int n)
{
MyStack st;
char arr[100] = { 0 };
int i = 0;
while (num > 0)
{
int cur = num % n;
if (cur < 10)
{
push(cur + '0', st);
}
else
{
push(cur - 10 + 'A', st);
}
num /= n;
}
while (!empty(st))
{
arr[i++] = top(st);
pop(st);
}
for (int j = 0; j <= i; j++) {
cout << arr[j];
}
cout << endl;
}
int main()
{
int num;
int n;
cin >> num >> n;
judge(num, n);
return 0;
}
记忆这道题,按模板记
3.括号匹配问题,也就是我压的一道题
#include <iostream>
#include <vector>
using namespace std;
typedef struct stnode
{
char data;
stnode* next;
stnode(char x) :data(x), next(nullptr){}
}stnode;
class st
{
public:
stnode* top;
st() :top(nullptr){}
bool empty()
{
return top == nullptr;
}
void push(char x)
{
stnode* newnode = new stnode(x);
newnode->next = top;
top = newnode;
}
char pop()
{
stnode* temp = top;
char val = temp->data;
top = top->next;
delete temp;
return val;
}
char tope()
{
return top->data;
}
~st()
{
while (!empty())
{
pop();
}
}
};
bool match(char left, char right)
{
return (left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}');
}
bool check(string s)
{
st mystack;
for (char c : s)
{
if (c == '(' || c == '[' || c == '{')
{
mystack.push(c);
}
else if (!mystack.empty() && match(mystack.tope(), c))
{
mystack.pop();
}
else
{
return false;
}
}
return mystack.empty();
}
int main()
{
string t;
cin >> t;
cout << (check(t) ? "YES" : "NO") << endl;
return 0;
}