程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

剑指offer:用两个栈实现队列

发布于2019-08-20 11:55     阅读(1045)     评论(0)     点赞(23)     收藏(1)


题目

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

解题思路

  1. 在push的时候两个栈都存入;
  2. 在pop的时候,判断Out栈是否为空,如果不为空则将Out栈更新为In栈[1:];,记录In栈[0]为res;
  3. In栈也更新为Out栈,返回res;
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stackIn = []
        self.stackOut = []
    def push(self, node):
        # write code here
        self.stackIn.append(node)
        self.stackOut.append(node)
        
    def pop(self):
        # return xx
        if len(self.stackOut)>0:
            self.stackOut = []
            res = self.stackIn[0]
            for i in range(1, len(self.stackIn)):
                self.stackOut.append(self.stackIn[i])
            self.stackIn = []
            for v in self.stackOut:
                self.stackIn.append(v)
        return res
            
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

简化了一下

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stackIn = []
        self.stackOut = []
    def push(self, node):
        # write code here
        self.stackIn.append(node)
        self.stackOut.append(node)
        
    def pop(self):
        # return xx
        if len(self.stackOut)>0:
            self.stackOut = []
            res = self.stackIn[0]
            self.stackOut = self.stackIn[1:]
            self.stackIn = []
            for v in self.stackOut:
                self.stackIn.append(v)
        return res
            
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21


所属网站分类: 技术文章 > 博客

作者:dfjdhfjdf

链接:https://www.pythonheidong.com/blog/article/49177/63053e8a6b965cf45a52/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

23 0
收藏该文
已收藏

评论内容:(最多支持255个字符)