Python实现栈和队列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python实现栈和队列相关的知识,希望对你有一定的参考价值。
栈:# -*- 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实现栈和队列的主要内容,如果未能解决你的问题,请参考以下文章