day10 记录代码随想录
第一题 232.用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
题目链接:力扣题目链接
栈:栈是一种先入后出的数据结构,是一种容器适配器,栈一般提供三种操作,压栈(push)、出栈(pop)、查看顶元素(top)。
队列:队列也是一种容器适配器,遵循先入先出的数据结构,队列一般提供四种操作,入列(push)、出列(pop)、查看第一个元素(front)、查看最后一个元素(back)
解题思路:
队列是先入先出的,可以使用两个栈来实现。
代码如下:
class MyQueue {
public:
MyQueue() { //构造函数
}
stack<int> stackIn;
stack<int> stackOut;
void push(int x) {
stackIn.push(x);
}
int pop() {
if(stackOut.empty())
while(!stackIn.empty()) {
stackOut.push(stackIn.top());
stackIn.pop();
}
int result;
result = stackOut.top();
stackOut.pop();
return result;
}
int peek() {
int result;
result = this->pop();
stackOut.push(result);
return result;
}
bool empty() {
return (stackIn.empty() && stackOut.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();
*/
第二题 225. 用队列实现栈
使用队列实现栈的下列操作:
- push(x) -- 元素 x 入栈
- pop() -- 移除栈顶元素
- top() -- 获取栈顶元素
- empty() -- 返回栈是否为空
题目链接:力扣题目链接
代码如下:
class MyStack {
public:
MyStack() {
}
queue<int> maque;
void push(int x) {
maque.push(x);
}
int pop() {
int size = maque.size();
size--;
while(size--) {
maque.push(maque.front());
maque.pop();
}
int result = maque.front();
maque.pop();
return result;
}
int top() {
int result = maque.back();
return result;
}
bool empty() {
return maque.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();
*/