用栈来实现队列
#include<iostream>
using namespace std;
#include<stack>
stack<int>input, output;
void push(int x)
{
input.push(x);
}
int pop()
{
while (!input.empty())
{
int p = input.top();
output.push(p);
input.pop();
}
int rsuult = output.top();
output.pop();
return rsuult;
}
int peak()
{
int res = pop();
output.push(res);
return res;
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int num;
cin >> num;
push(num);
}
cout << pop() << endl;
cout << peak() << endl;
}
用队列实现栈
#include<iostream>
using namespace std;
#include<queue>
class mystack
{
public:
queue<int>u;
mystack(){}
void push(int x)
{
u.push(x);
}
int pop()
{
int si_ze = u.size();
si_ze--;
while (si_ze--)
{
int x = u.front();
u.pop();
u.push(x);
}
int top = u.front();
u.pop();
return top;
}
int top()
{
return u.back();
}
bool empty()
{
return u.empty();
}
};
int main()
{
mystack v;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int num;
cin >> num;
v.push(num);
}
cout<<v.top();
cout<<v.pop();
cout<< v.empty();
}
有效的括号
#include<iostream>
using namespace std;
#include<stack>
#include<string >
int main()
{
stack<int>u;
string s;
cin >> s;
if (s.size() % 2 != 0)
{
cout << "不符合" << endl;
return 0;
}
for (int i = 0; i < s. size(); i++)
{
if (s[i] == '(')
{
u.push(')');
}
else if (s[i] == '{')
{
u.push('}');
}
else if (s[i] == '[')
{
u.push(']');
}
else if (u.empty() || u.top() != s[i])
{
cout << "不符合" << endl;
return 0;
}
else
u.pop();
}
cout << "符合" << endl;
return 0;
}
删除字符串中相邻的项
#include<iostream>
#include<stack>
#include<string >
#include<algorithm>
using namespace std;
int main()
{
string s;
cin >> s;
stack<int>u;
for (int i = 0; i < s.size(); i++)
{
if (u.empty()||s[i] != u.top() )
{
u.push(s[i]);
}
else {
u.pop();
}
}
string s2 = "";
//!!!
while (!u.empty())
{
s2 += u.top();
u.pop();
}
reverse(s2.begin(), s2.end());
cout << s2;
}
标签:Day9,队列,top,pop,int,用栈,num,push,include
From: https://blog.csdn.net/lxy2966201752/article/details/140108220