堆栈和队列(Python)

诈胡艺术 2020-11-13 03:19:56
Python CSDN 队列 堆栈


目录

【堆栈】

顺序栈

链栈

相关题目

【队列】

顺序队列

循环队列

链队列

相关题目

【递归】


 

【堆栈】

  • 顺序栈

实现和操作。

注:和线性表的区别只在于数据输入和输出的位置是固定的。

import ctypes
#顺序栈
class Stack():
def __init__(self):
self._capacity = 10
self._top = 0
self._A = self._make_array(self._capacity)
def isEmpty(self):
return self._top == 0
def push(self,value):
if self._top == self._capacity:
self._resize(self._capacity*2)
self._A[self._top] = value
self._top += 1
def pop(self):
if self.isEmpty():
raise Exception("no value")
else:
# value = self._A[self._top]
self._top -= 1
# return value
def clear(self):
while self._top:
self.pop()
def _make_array(self, c):
return (c* ctypes.py_object)()
def _resize(self, c):
B = self._make_array(c)
for i in range(self._top):
B[i] = self._A[i]
self._A = B
self._capacity = c
def _print(self):
for i in range(self._top):
print self._A[i],' ',
print ''

测试:

mystack = Stack()
mystack.push(1)
mystack.push(2)
mystack.push(3)
mystack.push(4)
mystack.push(5)
mystack.push(1)
mystack.push(2)
mystack.push(3)
mystack.push(4)
mystack.push(5)
mystack.push(1)
mystack.push(2)
mystack.push(3)
mystack.push(4)
mystack.push(5)
mystack._print()
mystack.pop()
mystack._print()
mystack.pop()
mystack._print()
mystack.pop()
mystack._print()
mystack.clear()
mystack._print()
  • 链栈

实现和操作。

#先定一个node的类
class Node(): #value + next
def __init__ (self, value = None, next = None):
self._value = value
self._next = next
def getValue(self):
return self._value
def getNext(self):
return self._next
def setValue(self,new_value):
self._value = new_value
def setNext(self,new_next):
self._next = new_next
#链栈
class LinkStack():
def __init__(self):
self._count = 0
self._top = None
def isEmpty(self):
return top == None
def push(self,value):
new_node = Node(value,self._top)
self._top = new_node
self._count += 1
def pop(self):
last = self._top
self._top = self._top.getNext()
self._count -= 1
last.next = None
def clear(self):
while self._top:
self.pop()
def _print(self):
current = self._top
while current:
print current.getValue(),'<-',
current = current.getNext()
print ''

测试:

my_linkstack = LinkStack()
my_linkstack.push(1)
my_linkstack.push(2)
my_linkstack.push(3)
my_linkstack.push(4)
my_linkstack.push(5)
my_linkstack._print()
my_linkstack.pop()
my_linkstack._print()
my_linkstack.pop()
my_linkstack._print()
my_linkstack.pop()
my_linkstack._print()
my_linkstack.clear()
my_linkstack._print()
  • 相关题目

逆波兰表达式求值

根据逆波兰表示法,求表达式的值。

class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
ret_list =[]
token = ['-','+','*','/']
for n in tokens:
if n in token:
second = ret_list.pop(-1)
first = ret_list.pop(-1)
if n == '-':
ret_list.append(first-second)
elif n=='+':
ret_list.append(first+second)
elif n=='*':
ret_list.append(first*second)
elif n=='/':
ret_list.append(int(first*1.0/second))
# if first*second<0 and first%second != 0:
# ret_list.append(first/second+1)
# else:
# ret_list.append(first/second)
else:
ret_list.append(int(n))
# print ret_list
return ret_list.pop(-1)

【队列】

  • 顺序队列

实现和操作:

import ctypes
#顺序队列
class Queue():
def __init__(self):
self._capacity = 10
self._last = 0
self._A = self._make_array(self._capacity)
def isEmpty(self):
return self._last==0
def isFull(self):
return self._last == self._capacity
def enterqueue(self,value):
if self.isFull():
raise Exception("full")
else:
self._A[self._last] = value
self._last += 1
def delqueue(self):
if self.isEmpty():
raise Exception("empty")
else:
for i in range(self._last-1):
self._A[i] = self._A[i+1]
self._last -= 1
def clear(self):
while self._last:
self.delqueue()
def _make_array(self, c):
return (c* ctypes.py_object)()
def _print(self):
for i in range(self._last):
print self._A[i],' ',
print ''

测试:

myqueuq = Queue()
myqueuq.enterqueue(1)
myqueuq.enterqueue(2)
myqueuq.enterqueue(3)
myqueuq.enterqueue(4)
myqueuq.enterqueue(5)
myqueuq.enterqueue(6)
myqueuq.enterqueue(7)
myqueuq.enterqueue(8)
myqueuq.enterqueue(9)
myqueuq.enterqueue(10)
myqueuq._print()
myqueuq.delqueue()
myqueuq._print()
myqueuq.delqueue()
myqueuq._print()
myqueuq.delqueue()
myqueuq.delqueue()
myqueuq._print()
myqueuq.clear()
myqueuq._print()
  • 循环队列

#循环队列
class CycleQueue():
def __init__(self):
self._capacity = 10
self._font = 0
self._rear = 0
self._A = self._make_array(self._capacity)
def isEmpty(self):
return self._rear==self._font
def isFull(self):
return (self._rear +1)%self._capacity==self._font
def enterqueue(self,value):
if self.isFull():
raise Exception("full")
else:
self._A[self._rear] = value
self._rear = (self._rear+1)%self._capacity
def delqueue(self):
if self.isEmpty():
raise Exception("empty")
else:
self._font = (self._font+1)%self._capacity
def clear(self):
while self._last:
self.delqueue()
def _make_array(self, c):
return (c* ctypes.py_object)()
def _print(self):
if self._font<self._rear:
print '<<<<<<<<'
for i in range(self._font,self._rear):
print self._A[i],' ',
elif self._font>self._rear:
print '>>>>>>>>>>>>'
for i in range(0,self._rear):
print self._A[i],' ',
print "zzz ",
for i in range(self._font,self._capacity):
print self._A[i],' ',
print ''

测试:

myqueuq = CycleQueue()
myqueuq.enterqueue(1)
myqueuq.enterqueue(2)
myqueuq.enterqueue(3)
myqueuq.enterqueue(4)
myqueuq.enterqueue(5)
myqueuq.enterqueue(6)
myqueuq.enterqueue(7)
myqueuq.enterqueue(8)
myqueuq.enterqueue(9)
myqueuq._print()
myqueuq.delqueue()
myqueuq._print()
myqueuq.enterqueue(100)
myqueuq._print()
myqueuq.delqueue()
myqueuq.delqueue()
myqueuq._print()
myqueuq.enterqueue(100)
myqueuq.enterqueue(100)
myqueuq._print()
  • 链队列

#链式队列
class LinkQueue():
def __init__(self):
self._font = Node()
self._rear = Node(next=self._font)
def isEmpty(self):
return self._rear.getNext()==self._font
def enterqueue(self,value):
new_node = Node(value)
self._rear.getNext().setNext(new_node)
self._rear.setNext(new_node)
def delqueue(self):
if self.isEmpty():
raise Exception("empty")
else:
del_node = self._font.getNext()
self._font.setNext(del_node.getNext())
del_node.setNext(None)
def clear(self):
while not self.isEmpty():
self.delqueue()
def _print(self):
current = self._font.getNext()
while current:
print current.getValue(),'->',
current = current.getNext()
print ''

测试:

myqueuq = LinkQueue()
myqueuq.enterqueue(1)
myqueuq.enterqueue(2)
myqueuq.enterqueue(3)
myqueuq.enterqueue(4)
myqueuq.enterqueue(5)
myqueuq.enterqueue(6)
myqueuq.enterqueue(7)
myqueuq.enterqueue(8)
myqueuq.enterqueue(9)
myqueuq._print()
myqueuq.delqueue()
myqueuq._print()
myqueuq.enterqueue(100)
myqueuq._print()
myqueuq.delqueue()
myqueuq.delqueue()
myqueuq._print()
  • 相关题目

设计循环双端队列】设计实现双端队列

class MyCircularDeque(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the deque to be k.
:type k: int
"""
self._A = []
self._countmax = k
def insertFront(self, value):
"""
Adds an item at the front of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull():
return False
else:
self._A.insert(0,value)
return True
def insertLast(self, value):
"""
Adds an item at the rear of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull():
return False
else:
self._A.append(value)
return True
def deleteFront(self):
"""
Deletes an item from the front of Deque. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty():
return False
else:
self._A.pop(0)
return True
def deleteLast(self):
"""
Deletes an item from the rear of Deque. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty():
return False
else:
self._A.pop()
return True
def getFront(self):
"""
Get the front item from the deque.
:rtype: int
"""
if self.isEmpty():
return -1
else:
return self._A[0]
def getRear(self):
"""
Get the last item from the deque.
:rtype: int
"""
if self.isEmpty():
return -1
else:
return self._A[-1]
def isEmpty(self):
"""
Checks whether the circular deque is empty or not.
:rtype: bool
"""
return len(self._A) == 0
def isFull(self):
"""
Checks whether the circular deque is full or not.
:rtype: bool
"""
return len(self._A) == self._countmax

【递归】

爬楼梯

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注:重点在于迭代的条件以及迭代终止的输出。有时候因为迭代过深可能会出现问题,可以采用相应的矩阵或者一维数组存放计算结果。

class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
fun = [1]*n
for nn in range(n):
if nn == 0:
fun[nn] = 1
elif nn == 1:
fun[nn] = 2
else:
fun[nn] = fun[nn-1]+fun[nn-2]
return fun[-1]

 

版权声明
本文为[诈胡艺术]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_38019841/article/details/88065955

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database