Amanda-Zhang
追梦女一枚

力扣每日一题-两个栈模拟队列

2021-03-12 -leetcode -算法
Word count: 194 | Reading time: 1min
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//两个数组模拟栈的行为
var stack1=[],//存储栈
stack2=[];//辅助栈

//栈是后入先出(LIFO,last in first out),队列是先入先出(FIFO,first in first out)

//队列插入元素函数
function push(ele)
{
//模拟队列的push操作,直接往存储栈stack1中推入即可
//但是要考虑辅助栈stack2中还存在值的情况,需要先将辅助栈中的值推回存储栈中
while(stack2.length !== 0){
stack1.push(stack2.pop());
}
stack1.push(ele);
}
//队列删除元素函数
function pop()
{
//模拟队列的pop操作则要考虑栈的后入先出特性,需要先将存储栈stack1中的数组,推入辅助栈stack2,然后辅助栈弹出元素
while(stack1.length !== 0){
stack2.push(stack1.pop());
}
return stack2.pop();
}

Author: Amanda-Zhang

Link: http://chunchunya.github.io/2021/03/12/3_12%20%E4%B8%A4%E4%B8%AA%E6%A0%88%E6%A8%A1%E6%8B%9F%E9%98%9F%E5%88%97/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
牛客常见的输入输出
NextPost >
力扣每日一题-二分查找类型题目
CATALOG