0
点赞
收藏
分享

微信扫一扫

[数组]BM42 用两个栈实现队列-简单

秀儿2020 2022-06-17 阅读 129

​​BM42 用两个栈实现队列​​

描述

用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。

数据范围: [数组]BM42 用两个栈实现队列-简单_队列要求:存储n个元素的空间复杂度为 [数组]BM42 用两个栈实现队列-简单_队列_02 ,插入与删除的时间复杂度都是 [数组]BM42 用两个栈实现队列-简单_队列_03

示例1

输入:

["PSH1","PSH2","POP","POP"]

复制返回值:

1,2

复制说明:

"PSH1":代表将1插入队列尾部
"PSH2":代表将2插入队列尾部
"POP“:代表删除一个元素,先进先出=>返回1
"POP“:代表删除一个元素,先进先出=>返回2

示例2

输入:

["PSH2","POP","PSH1","POP"]

复制返回值:

2,1

题解

  • push时,直接将数据放入栈in中
  • pop时,如果out栈不为空,直接弹出栈顶元素,否则将in中的元素挨个push到out中之后再取out的栈顶元素
// https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=295&tqId=23281&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295

#include <bits/stdc++.h>

using namespace std;

class queue_1
{
public:
void push(int node)
{
while (!out.empty())
{
in.push(out.top());
out.pop();
}
in.push(node);
while (!in.empty())
{
out.push(in.top());
in.pop();
}
}

int pop()
{
int t = out.top();
out.pop();
return t;
}

private:
stack<int> in;
stack<int> out;
};

class Solution
{
public:
void push(int node)
{
in.push(node);
}

int pop()
{
if (!out.empty())
{
int n = out.top();
out.pop();
return n;
}

while (!in.empty())
{
out.push(in.top());
in.pop();
}
int n = out.top();
out.pop();
return n;
}

private:
stack<int> in;
stack<int> out;
};
举报

相关推荐

0 条评论