数据结构之栈总结(Python实现)
作者:互联网
栈是链表的一种应用,栈的数据结构类型就是链表。
特点:先进后出。就像一个瓶子,瓶底的是先进去,最后出来。
那么对栈的响应操作就没有那么多了,只有入栈,出栈,遍历,计算长度。
下面通过代码来实现:
#节点实现
class Node(object):
def __init__(self,i):
self.val = i
self.next = None
#栈实现
class stack(object):
def __init__(self,node):
self.head = node
def append_s(self,i):
node = Node(i)
cur = self.head
if cur.next == None:
cur.next = node
return
while cur.next != None:
cur = cur.next
cur.next = node
#弹栈
def pop_s(self):
cur = self.head
pre = cur
if cur.next == None:
self.head = None
return
while cur.next != None:
pre = cur
cur = cur.next
pre.next = None
#计算栈中的元素长度
def len_s(self):
count = 0
cur = self.head
while cur != None:
count += 1
cur = cur.next
return count
#对栈进行遍历
def travel_s(self):
cur = self.head
while cur != None:
print(cur.val)
cur = cur.next
node = Node(1)
s = stack(node)
print(s.len_s())
s.travel_s()
s.append_s(2)
print(s.len_s())
s.travel_s()
运行结果:
1
1
2
1
2
标签:node,None,cur,Python,self,之栈,head,next,数据结构 来源: https://blog.csdn.net/weixin_43726471/article/details/121293979