Java和Cpp中栈与队列的区别
题目
1.225. 用队列实现栈
2.232. 用栈实现队列
3.155. 最小栈
思路与算法
- 三道简单力扣习题之前用Java提交过题解,这次用Cpp来进行提交,从而加深二者的stl或者是对应的util工具类中的方法的使用。
代码实现
1.225. 用队列实现栈
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
std::queue<int> tmp_queue;
tmp_queue.push(x);
while (!_data.empty()) {
tmp_queue.push(_data.front());
_data.pop();
}
while (!tmp_queue.empty()) {
_data.push(tmp_queue.front());
tmp_queue.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = _data.front();
_data.pop();
return x;
}
/** Get the top element. */
int top() {
return _data.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return _data.empty();
}
private:
std::queue<int> _data;
};
/**
* 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();
*/
2.232. 用栈实现队列
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
std::stack<int> tmp_stack;
while (!_data.empty()) {
tmp_stack.push(_data.top());
_data.pop();
}
tmp_stack.push(x);
while (!tmp_stack.empty()) {
_data.push(tmp_stack.top());
tmp_stack.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int x = _data.top();
_data.pop();
return x;
}
/** Get the front element. */
int peek() {
return _data.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return _data.empty();
}
private:
std::stack<int> _data;
};
/**
* 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();
*/
3.155. 最小栈
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
_data.push(x);
if (minStack.empty()) {
minStack.push(x);
} else {
if (x > minStack.top()) {
x = minStack.top();
}
minStack.push(x);
}
}
void pop() {
_data.pop();
minStack.pop();
}
int top() {
return _data.top();
}
int getMin() {
return minStack.top();
}
private:
std::stack<int> _data;
std::stack<int> minStack;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
对比分析两种语言中栈和队列的区别
-
栈的区别
-
队列的区别