剑指 队列生成栈

用两个栈实现队列

http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

需要自己定义def __ init__() 类的属性,然后push 操作直接放入self.stack1 当取出的时候,需要判断stack2中是否有元素 如果有直接取出 ,如果没有,则将self.stack1中元素放入self.stack2中再进行取出。

# -*- 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):

        if len(self.stack2)==0:
            if len(self.stack1)==0:
                return False
            else:
                while self.stack1:
                    self.stack2.append(self.stack1[-1])
                    self.stack1.pop()



        result=self.stack2[-1]
        self.stack2.pop()
        return result         
        # return xx

直接获取pop的值

# -*- 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):

        if len(self.stack2)==0:
            if len(self.stack1)==0:
                return False
            else:
                while self.stack1:
                    self.stack2.append(self.stack1.pop())
                    #self.stack1.pop()

        #result=self.stack2[-1]

        return self.stack2.pop()       
        # return xx
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务