用栈实现队列
class MyQueue {
public:
MyQueue()
{}
void push(int x)
{
stIn.push(x);
}
int pop()
{
int a;
while(!stIn.empty())
{
a = stIn.top();
stIn.pop();
stOut.push(a);
}
a = stOut.top();
stOut.pop();
while(!stOut.empty())
{
int b = stOut.top();
stOut.pop();
stIn.push(b);
}
return a;
}
int peek()
{
int a;
while(!stIn.empty())
{
a = stIn.top();
stIn.pop();
stOut.push(a);
}
a = stOut.top();
while(!stOut.empty())
{
int b = stOut.top();
stOut.pop();
stIn.push(b);
}
return a;
}
bool empty()
{
return stIn.empty() && stOut.empty();
}
stack<int> stIn;
stack<int> stOut;
};
用队列实现栈
class MyStack {
public:
MyStack()
{
_size = 0;
}
void push(int x)
{
que.push(x);
++_size;
}
int pop()
{
int x;
for(int i = 0; i < que.size() - 1; ++i)
{
x = que.front();
que.pop();
que.push(x);
}
x = que.front();
que.pop();
--_size;
return x;
}
int top()
{
int x = this->pop();
que.push(x);
return x;
}
bool empty()
{
return que.empty();
}
private:
queue
int _size;
};
有效的括号
class Solution {
public:
bool isValid(string s)
{
for(int i = 0; i < s.size(); ++i)
{
if(s[i] == '(')
{
st.push(')');
}
else if(s[i] == '[')
{
st.push(']');
}
else if(s[i] == '{')
{
st.push('}');
}
else
{
if(st.empty())
{
return false;
}
else
{
char ch = st.top();
st.pop();
if(ch != s[i])
{
return false;
}
}
}
}
return st.empty();
}
private:
stack
};
删除字符串的相邻重复项
class Solution {
public:
string removeDuplicates(string s)
{
for(int i = 0; i < s.size(); ++i)
{
if(_st.empty())
{
_st.push(s[i]);
}
else
{
char ch = _st.top();
if(ch == s[i])
{
_st.pop();
}
else
{
_st.push(s[i]);
}
}
}
string ret;
while(!_st.empty())
{
char ch = _st.top();
ret += ch;
_st.pop();
}
reverse(ret.begin(), ret.end());
return ret;
}
private:
stack
};