一 栈
① 什么是栈:一种可以实现先进后出的数据结构。
栈类似于一个箱子,先放进去的书,最后才能取出来,同理,后放进去的书,先取出来
② 栈的分类:静态栈和动态栈
静态栈:
静态栈的核心是数组,类似于一个连续内存的数组,我们只能操作其栈顶元素。
动态栈:
动态栈的核心是链表。
③ 栈的算法:
栈的算法主要是压栈和出栈两种操作:
那么对于栈的操作,我们应该知道:
1、栈操作的对象是一个一个的节点。
2、栈本身也是一种存储的数据结构。
3、栈有 初始化、压栈、出栈、判空、遍历、清空等主要方法
class Stack(object): def __init__(self): self.pTop = None self.pBottom = None class Node(object): def __init__(self, data=None, pNext = None): self.data = data self.pNext = pNext def push(s, new): new.pNext = s.pTop s.pTop = new def pop(s): cur = s.pTop # while cur != s.pBottom: # if cur.data == val: # s.pTop = cur.pNext # break # cur = cur.pNext # else: # print('没有找到此元素') while cur != s.pBottom: s.pTop = cur.pNext print("出栈的元素是: %d" % cur.data) cur = cur.pNext else: print("出栈失败") def getAll(s): cur = s.pTop while cur != s.pBottom: print(cur.data) cur = cur.pNext def is_empty(s): if s.pTop == s.pBottom: return True else: return False def clear(s): if is_empty(s): return None p = s.pTop q = None while p != s.pBottom: q = p.pNext del p p = q else: s.pBottom = s.pTop head = Node() s = Stack() s.pTop = s.pBottom = head n1 = Node(2) push(s, n1) n1 = Node(5) push(s, n1) n1 = Node(89) push(s, n1) print("##############遍历元素##########") getAll(s) # print("##############出栈元素#######") # pop(s) print("##############清空栈##########") clear(s) print("##############遍历元素##########") getAll(s)