课程:【Udemy高分付费课程】Python数据结构与算法 - 终极 Python 编码面试和计算机科学训练营(中英文字幕)_哔哩哔哩_bilibili
栈的基本结构
基础代码
class Node:
def __init__(self,value):
self.value=value
self.next=None
class Stack:
def __init__(self,value):
new_node=Node(value)
self.top=new_node
self.height=1
def print_stack(self):
temp=self.top
while temp is not None:
print(temp.value)
temp=temp.next
添加一个数值 push
def push(self,value):
new_node=Node(value)
if self.height==0:
self.top=new_node
else:
new_node.next=self.top
self.top=new_node
self.height+=1
my_stack=Stack(2)
my_stack.push(1)
my_stack.push(1)
my_stack.push(5)
my_stack.print_stack()
删除一个数值 pop
def pop(self):
if self.height==0:
return None
temp=self.top
self.top=self.top.next
temp.next=None
self.height-=1
return temp
my_stack=Stack(2)
my_stack.push(1)
my_stack.push(1)
my_stack.push(5)
my_stack.pop()
my_stack.print_stack()
完整代码
class Node:
def __init__(self,value):
self.value=value
self.next=None
class Stack:
def __init__(self,value):
new_node=Node(value)
self.top=new_node
self.height=1
def print_stack(self):
temp=self.top
while temp is not None:
print(temp.value)
temp=temp.next
def push(self,value):
new_node=Node(value)
if self.height==0:
self.top=new_node
else:
new_node.next=self.top
self.top=new_node
self.height+=1
def pop(self):
if self.height==0:
return None
temp=self.top
self.top=self.top.next
temp.next=None
self.height-=1
return temp