码迷,mamicode.com
首页 > 编程语言 > 详细

Python实现栈和队列

时间:2019-05-16 16:27:08      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:obj   return   []   main   utf-8   add   coding   code   int   

栈:

# -*- coding:utf-8 -*-
class Stack(object):
    def __init__(self):
        self.__list = []
    def push(self,item):
        return self.__list.append(item)
    def pop(self):
        return self.__list.pop()
    def peek(self):
        """返回栈顶元素"""
        if self.__list:
            return self.__list[-1]
        else:
            return None
    def is_empty(self):
        """判断栈是否为空"""
        return  self.__list == []
    def size(self):
        return len(self.__list)

if __name__=="__main__":
    s=Stack()
    print(s.is_empty())
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
    print(s.is_empty())
    print(s.pop())
    print(s.pop())
    print(s.pop())
    print(s.pop())

# True
# False
# 4
# 3
# 2
# 1

队列:

# -*- coding:utf-8 -*-
class Queue(object):
    """单队列"""
    def __init__(self):
        self.__list = []
    def inquene(self,item):
        return self.__list.insert(0,item)
    def dequeue(self):
        return self.__list.pop()
    def is_empty(self):
        return self.__list == []
    def size(self):
        return len(self.__list)

class DQueue(object):
    """双端队列"""
    def __init__(self):
        self.__list = []
    def add_front(self,item):
        return self.__list.insert(0,item)
    def add_rear(self,item):
        return self.__list.append(item)
    def pop_front(self):
        return self.__list.pop(0)
    def pop_rear(self):
        return self.__list.pop( )
    def is_empty(self):
        return self.__list == []
    def size(self):
        return len(self.__list)

if __name__ == "__main__":
    q=Queue()
    q.inquene(1)
    q.inquene(2)
    q.inquene(3)
    q.inquene(4)
    q.size()
    q.is_empty()
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())

    d=DQueue()
    d.add_front(1)
    d.add_front(2)
    d.add_rear(3)
    d.add_rear(4)
    print(d.pop_rear())
    print(d.pop_rear())
    print(d.pop_rear())
    print(d.pop_rear())

# 1
# 2
# 3
# 4
# 4
# 3
# 1
# 2

Python实现栈和队列

标签:obj   return   []   main   utf-8   add   coding   code   int   

原文地址:https://blog.51cto.com/10777193/2395731

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!