leetcode 155. Min Stack 、232. Implement Queue using Stacks 、225. Implement Stack using Queues

时间:2023-03-08 23:42:49
leetcode 155. Min Stack 、232. Implement Queue using Stacks 、225. Implement Stack using Queues

155. Min Stack

class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
} void push(int x) {
if(s1.empty() && s2.empty()){
s1.push(x);
s2.push(x);
}
else{
if(x < s2.top()){
s1.push(x);
s2.push(x);
}
else{
s1.push(x);
s2.push(s2.top());
}
}
} void pop() {
s1.pop();
s2.pop();
return;
} int top() {
return s1.top();
} int getMin() {
return s2.top();
}
stack<int> s1,s2;
};

232. Implement Queue using Stacks

class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() { } /** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
} /** Removes the element from in front of queue and returns that element. */
int pop() {
if(s2.empty())
shiftstack();
int tmp = s2.top();
s2.pop();
return tmp;
} /** Get the front element. */
int peek() {
if(s2.empty())
shiftstack();
return s2.top();
} /** Returns whether the queue is empty. */
bool empty() {
return s1.empty() && s2.empty() ? true : false;
} void shiftstack(){
if(s1.empty())
return;
while(!s1.empty()){
int tmp = s1.top();
s1.pop();
s2.push(tmp);
}
return;
} stack<int> s1,s2;
};

225. Implement Stack using Queues

将存储的队列之前的数值再次加入到队列的末尾

class MyStack {
public:
/** Initialize your data structure here. */
MyStack() { } /** Push element x onto stack. */
void push(int x) {
q.push(x);
for(int i = ;i < q.size() - ;i++){
int tmp = q.front();
q.pop();
q.push(tmp);
}
return;
} /** Removes the element on top of the stack and returns that element. */
int pop() {
int tmp = q.front();
q.pop();
return tmp;
} /** Get the top element. */
int top() {
return q.front();
} /** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
queue<int> q;
};

http://www.cnblogs.com/grandyang/p/4568796.html