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

python 栈的理解与使用

时间:2021-05-24 09:57:27      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:堆和栈   创建   main   elf   pytho   ==   pen   ini   false   

title: ①解决字符串的翻转

②堆和栈的区别?

 

>>> class Stack:
	def __init__(self):
		self.item = []
	def isEmpty(self):
		return len(self.item)==0
	def push(self,item):
		self.item.append(item)
	def pop(self):
		self.item.pop()
	def peek(self):
		if not self.isEmpty():
			return self.item[len(self.item)-1]
	def size(self):
		return len(self.item)

	
>>> s=Stack()
>>> type(s)
<class ‘__main__.Stack‘>
>>> print(s)
<__main__.Stack object at 0x000002675BC61FD0>
>>> s.isEmpty()
True
>>> s.push(4)
>>> s.push(‘dog‘)
>>> s.peek()
‘dog‘
>>> s.pop()
>>> s.peek()
4
>>> s.isEmpty()
False
>>> s.size()
1
>>> 

class Node(object):
def __init__(self, data, next = None):
self.data = data
self.next = next

class Stack(object):
def __init__(self, top = None):
self.top = top

def push(self,data):
#创建新的节点放到栈顶
self.top = Node(data, self.top)

def pop(self):
#拿出栈顶元素,原来的栈发生改变
if self.top is None:
return None
data = self.top.data
self.top = self.top.next
return data

def peek(self):
#查看栈顶元素,原来的栈不变
return self.top.data if self.top is not None else None

def isEmpty(self):
return self.peek() is None


if __name__ == "__main__":
stack = Stack()
stack = Stack()
print(type(stack))
stack1 = stack.push(1)
stack1 = stack.push(2)
print(stack.peek()) #查看栈顶元素
print("---------------")
stack.pop()
print(stack.peek())
print(stack.isEmpty())
print("dddddd")



  

python 栈的理解与使用

标签:堆和栈   创建   main   elf   pytho   ==   pen   ini   false   

原文地址:https://www.cnblogs.com/pink-123/p/14770490.html

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