232:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty)
简单题:用两个栈,倒进去再拿出来,就是队列顺序啦!
怎么倒一下呢?就是先把饼干一个个放到第一个桶里,第二个桶拿光了以后,把第一个桶里的饼干一片片拿出来放到第二个桶里。
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
sin.push(x);
}
int pop() {
if(sout.empty()) in_out();
int x=sout.top();
sout.pop();
return x;
}
int peek() {
if(sout.empty()) in_out();
return sout.top();
}
bool empty() {
return sin.empty()&&sout.empty();
}
private:
stack<int> sin,sout;
void in_out(){
while(!sin.empty()){
sout.push(sin.top());
sin.pop();
}
}
};
难度中等731 (其实是想到了蛇形遍历那道题)
给你二叉树的根节点
root
,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
思路1:还是以层序遍历顺序访问,利用奇偶标记位,用deque实现双向存储;
deque 是一个双向队列!这里还用到了vector的类型转换!
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(!root) return ans;
queue<TreeNode*> Que;
Que.push(root);
bool flag=1;// 1:正向 0: 反向
while(!Que.empty()){
//每一层的层序遍历
deque<int> list;
int k=Que.size();
for(int i=0;i<k;i++){
TreeNode* p=Que.front();
Que.pop();
if(flag) list.push_back(p->val);
else list.push_front(p->val);
if(p->left) Que.push(p->left);
if(p->right) Que.push(p->right);
}
ans.emplace_back(vector<int>{ list.begin(),list.end()});//格式转换 ;存储结果
flag=!flag;// 标志位转换
}
return ans;
}
};
思路2: 也是两个栈;
public ArrayList<ArrayList<Integer>> Print(TreeNodes pRoot) {
// 先右后左
Stack<TreeNodes> s1 = new Stack<TreeNodes>();
// 先左后右
Stack<TreeNodes> s2 = new Stack<TreeNodes>();
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
list.add(pRoot.val);
s1.push(pRoot);
while (s1.isEmpty() || s2.isEmpty()) {
if (s1.isEmpty() && s2.isEmpty()) {
break;
}
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
if (s1.peek().right != null) {
list.add(s1.peek().right.val);
s2.push(s1.peek().right);
}
if (s1.peek().left != null) {
list.add(s1.peek().left.val);
s2.push(s1.peek().left);
}
s1.pop();
}
} else {
while (!s2.isEmpty()) {
if (s2.peek().left != null) {
list.add(s2.peek().left.val);
s1.push(s2.peek().left);
}
if (s2.peek().right != null) {
list.add(s2.peek().right.val);
s1.push(s2.peek().right);
}
s2.pop();
}
}
}
return list;
}
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(
push
、top
、pop
和empty
)。
class MyStack {
public:
MyStack() {
}
//实现q1的反转
void push(int x) {
q2.push(x);
while(!q1.empty()){
q2.push(q1.front());
q1.pop();
}
swap(q1,q2);
}
int pop() {
int x=q1.front();
q1.pop();
return x;
}
int top() {
int x=q1.front();
return x;
}
bool empty() {
return q1.empty();
}
private:
queue<int> q1,q2;
};