剑指offer 66道-python+JavaScript
两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
分别用python和javascript实现
github
python代码链接: https://github.com/seattlegirl/jianzhioffer/blob/master/implement-Quene-using-stacks.py.
题目代码(python)
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1=[]
self.stack2=[]
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
while(self.stack1):
self.stack2.append(self.stack1.pop())
res=self.stack2.pop()
while(self.stack2):
self.stack1.append(self.stack2.pop())
return res
github
JavaScript代码链接: https://github.com/seattlegirl/jianzhioffer/blob/master/implement-Quene-using-stacks.js.
题目代码(JavaScript)
var stack1=[];//新建两个数组
var stack2=[];
function push(node)
{
// write code here
stack1.push(node) //push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
}
function pop()
{
// write code here
//pop() 方法用于删除数组的最后一个元素并返回删除的元素。
//shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。
if(stack1.length==0){
return false
}
return stack1.shift()
}