栈
需要头文件
#include<stack>
栈的定义
stack<储存的类型> 容器名
在缺省时默认用deque实现栈,deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。
其他实现方法还有vector(顺序栈)
和list(链栈)
规定链栈没有虚拟头节点,head直接指向栈顶,
Status Push(ElemType e) {
StackNode* p = new StackNode(); // 分配新的结点
if (p == nullptr) {
throw std::runtime_error("Memory allocation failed!");
}
p->data = e;
p->next = top; // 将当前的栈顶元素赋值给新节点的直接后继
top = p; // 将新的结点赋值给栈顶指针
count++;
return OK;
链栈
head
stack<int,vector<int>> x;//指定使用vector来实现栈
栈的函数
push(): 在栈顶添加一个元素。
pop(): 移除栈顶元素。
top(): 返回栈顶元素的引用,但不移除它。
empty(): 检查栈是否为空。
size(): 返回栈中元素的数量
queue
初始化
queue<Type, Container> (<数据类型,容器类型>)
//其中容器类型缺省为deque
不能用vector容器初始化queue
常用函数
push() 在队尾插入一个元素
pop() 删除队列第一个元素
size() 返回队列中元素个数
empty() 如果队列空则返回true
front() 返回队列中的第一个元素
back() 返回队列中最后一个元素
232.用栈实现队列
思路:
用两个栈,一个栈正常推入,
当要弹出队列首元素时,则将第一个栈按顺序填入第二个栈,这样首元素来到栈顶,可以弹出。
#include <stack>
class MyQueue {
public:
MyQueue() {}
void push(int x) {
stackin.push(x); //|1,2,3,4....
}
int pop() {
if (stackout.empty() == false) {
int ans = stackout.top();
stackout.pop();
return ans;
}
while (stackin.empty() == false) {
stackout.push(stackin.top()); // ...1,2,3,4|
stackin.pop();
}
int ans = stackout.top();
stackout.pop();
return ans;
}
int peek() {
int ans=this->pop();//peek和pop逻辑一样,可以抽象出来
stackout.push(ans);
return ans;
}
bool empty() {
if (stackin.empty() == true && stackout.empty() == true)
return true;
else
return false;
}
private:
stack<int> stackin;
stack<int> stackout;
};
225.用队列实现栈
因为队列只能从第一个出,再放进第二个队列时他们的相对位置是不变的,所以可以看当前队列中有多少个元素
假如有n个,移动前n-1个到队列2中,然后队列1中front()得到的就是栈的末尾元素。接着再把队列2放回队列1.
也可以只用一个队列,队列中出来的元素排到末尾。
int pop() {
int time=queue2.size()-1;
while(time--){
queue2.push(queue2.front());//让前面n-1个重新列入队列2
queue2.pop();
}
int ans=queue2.front();
queue2.pop();
return ans;
}
20.有效的括号
有效的括号
不匹配的情况:
1.左边多了(右边少了)
2.两个左右不匹配了(】或者({}】
3.右边多了
可以用栈来解决:
当出现左括号时,将其相应右括号填入栈,碰到右括号时则和末尾比较,不相同返回false,若相同则弹出,如果最后empty==true,则完全匹配
stack<char> first;
if(s.size()%2==1)
return false;
for(int i=0;i<s.size();i++){
if(s[i]=='(')
first.push(')');
else if(s[i]=='[')
first.push(']');
else if(s[i]=='{')
first.push('}');
else{
if(first.empty()==true){
return false;
}
else if(first.top()!=s[i]){
return false;
}
else
first.pop();
}
}
return first.empty();
1047.删除字符串
写了上面那道再来写这道就容易多了,利用栈的思路,将字符串填入栈中
如果top与要填的字母相同,则消掉,
stack<char> st;
for(int i=0;i<s.size();i++){
if(st.empty()||st.top()!=s[i])
st.push(s[i]);//没有字母时或不同时就
else {
st.pop();
}
}
string ans(st.size(),'0');//注意string的初始化不能只给个大小,还要给填入什么。
for(int j=st.size()-1;j>=0;j--){//倒着填入
ans[j]=st.top();
st.pop();
}
return ans;