【leetcode】栈232,python实现两个栈满足队列的特点

问题描述:仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(pushpoppeekempty),

     实现 MyQueue 类:

     void push(int x) 将元素 x 推到队列的末尾
     int pop() 从队列的开头移除并返回元素
     int peek() 返回队列开头的元素
       boolean empty() 如果队列为空,返回 true ;否则,返回 false

问题解析:队列的特点是一端只能入队列,另一端只能出队列,应满足先进先出。而栈是只能在一端进行操作,于是先进后出;

     定义两个栈分别为stack_a 和 stack_b,stack_a用来存入数据,从stack_b里取出数据。即满足题意。

code:

 1 class MyQueue:
 2 
 3     def __init__(self):
 4         """
 5         Initialize your data structure here.
 6         """
 7         self.stack_a = [] #用于保存数据
 8         self.stack_b = [] #用于提取数据
 9 
10 
11     def push(self, x: int) -> None:
12         """
13         Push element x to the back of queue.
14         """
15         self.stack_a.append(x)
16 
17 
18     def pop(self) -> int:
19         """
20         Removes the element from in front of queue and returns that element.
21         """
22         if len(self.stack_b)==0:
23             while len(self.stack_a)>0:
24                 x=self.stack_a.pop()
25                 self.stack_b.append(x)
26         return self.stack_b.pop()
27 
28 
29     def peek(self) -> int:
30         """
31         Get the front element.
32         """
33         if len(self.stack_b)>0:
34             return self.stack_b[-1]
35         else:
36             return self.stack_a[0]
37 
38 
39     def empty(self) -> bool:
40         """
41         Returns whether the queue is empty.
42         """
43         if len(self.stack_a)== 0 and len(self.stack_b)==0 :
44             return True
45         else:
46             return False

补充:python类中的3个方法:

   对象方法(实例方法):默认有个self参数,可以操作实例属性和类属性 ,只能被实例对象调用;

   类方法:默认有个 cls 参数,可以被类和对象调用,需要加上 @classmethod 装饰器。

   静态方法: 用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法,类的静态方法可以没有参数,可以直接使用类名调用。

# coding:utf-8
class Foo(object):
    """类三种方法语法形式"""
 
    def instance_method(self):
        print("是类{}的实例方法,只能被实例对象调用".format(Foo))
 
    @staticmethod
    def static_method():
        print("是静态方法")
 
    @classmethod
    def class_method(cls):
        print("是类方法")
 
foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()

 

posted @ 2021-03-06 15:04  ambi023  阅读(80)  评论(0)    收藏  举报