提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
LeetCode232.用栈实现队列
class MyQueue {
private:
stack<int> s;
stack<int> buffer;
public:
MyQueue() {
}
void push(int x) {
s.push(x);
}
int pop() {
while(!s.empty()){
int temp = s.top();
s.pop();
buffer.push(temp);
}
int result = buffer.top();
buffer.pop();
while(!buffer.empty()){
int temp = buffer.top();
buffer.pop();
s.push(temp);
}
return result;
}
int peek() {
while(!s.empty()){
int temp = s.top();
s.pop();
buffer.push(temp);
}
int result = buffer.top();
while(!buffer.empty()){
int temp = buffer.top();
buffer.pop();
s.push(temp);
}
return result;
}
bool empty() {
return s.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
LeetCode225.用队列实现栈
class MyStack {
private:
queue<int> q;
queue<int> buffer;
public:
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
while(q.size() > 1){
int temp = q.front();
q.pop();
buffer.push(temp);
}
int result = q.front();
q.pop();
while(!buffer.empty()){
int temp = buffer.front();
buffer.pop();
q.push(temp);
}
return result;
}
int top() {
while(q.size() > 1){
int temp = q.front();
q.pop();
buffer.push(temp);
}
int result = q.front();
q.pop();
buffer.push(result);
while(!buffer.empty()){
int temp = buffer.front();
buffer.pop();
q.push(temp);
}
return result;
}
bool empty() {
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
LeetCode20.有效的括号
class Solution {
public:
bool isValid(string s) {
stack<char> c_stack;
for(int i = 0; i < s.length(); i++){
if(s[i] == '('||s[i] == '[' || s[i] == '{'){
c_stack.push(s[i]);
}else if(s[i] == ')'){
if(!c_stack.empty()&&c_stack.top() == '('){
c_stack.pop();
}else{
return false;
}
}else if(s[i] == ']'){
if(!c_stack.empty()&&c_stack.top() == '['){
c_stack.pop();
}else{
return false;
}
}else if(s[i] == '}'){
if(!c_stack.empty()&&c_stack.top() == '{'){
c_stack.pop();
}else{
return false;
}
}
}
if(c_stack.empty())
return true;
else
return false;
}
};
LeetCode1047.删除字符串中所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
string result = "";
stack<char> s_char;
for(int i = 0; i < s.length(); i++){
if(s_char.empty()||s_char.top()!=s[i]){
s_char.push(s[i]);
}else if(s_char.top() == s[i]){
s_char.pop();
}
}
while(!s_char.empty()){
result += s_char.top();
s_char.pop();
}
reverse(result.begin(),result.end());
return result;
}
};