-
将元素推入堆栈。
-
从堆栈中删除一个元素。
要检查的条件
-
溢出情况—— 当我们试图在一个已经有最大元素的堆栈中再放一个元素时,就会出现这种情况。
-
下溢情况——当 我们试图从一个空堆栈中删除一个元素时,就会出现这种情况。
class mystack:
def init(self):
self.data =[]
def length(self): #length of the list
return len(self.data)
def is_full(self): #check if the list is full or not
if len(self.data) == 5:
return True
else:
return False
def push(self, element):# insert a new element
if len(self.data) < 5:
self.data.append(element)
else:
return “overflow”
def pop(self): # # remove the last element from a list
if len(self.data) == 0:
return “underflow”
else:
return self.data.pop()
a = mystack() # I create my object
a.push(10) # insert the element
a.push(23)
a.push(25)
a.push(27)
a.push(11)
print(a.length())
print(a.is_full())
print(a.data)
print(a.push(31)) # we try to insert one more element in the list - the
output will be overflow
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop()) # try to delete an element in a list without elements - the
output will be underflow
使用数组排队
队列是一种线性数据结构,其中的元素按顺序排列。它遵循先进先出的F.I.F.O机制。
描述队列特征的方面
两端:
-
前端-指向起始元素。
-
指向最后一个元素。
有两种操作:
-
enqueue——将元素插入队列。它将在后方完成。
-
出列-从队列中删除元素。这将在前线完成。
有两个条件。
-
溢出-插入到一个已满的队列中。
-
下溢-从空队列中删除。
class myqueue:
def init(self):
self.data = []
def length(self):
return len(self.data)
def enque(self, element): # put the element in the queue
if len(self.data) < 5:
return self.data.append(element)
else:
return “overflow”
def deque(self): # remove the first element that we have put in queue
if len(self.data) == 0:
return “underflow”
else:
self.data.pop(0)
b = myqueue()
b.enque(2) # put the element into the queue
b.enque(3)
b.enque(4)
b.enque(5)
print(b.data)
b.deque()# # remove the first element that we have put in the queue
print(b.data)
树(普通树)
树用于定义层次结构。它从根节点开始,再往下,最后的节点称为子节点。
在本文中,我主要关注二叉树。二叉树是一种树形数据结构,其中每个节点最多有两个孩子,称为左孩子和右孩子。
create the class Node and the attrbutes
class Node:
def init(self, letter):
self.childleft = None
self.childright = None
self.nodedata = letter
create the nodes for the tree
root = Node(‘A’)
root.childleft = Node(‘B’)
root.childright = Node(‘C’)
root.childleft.childleft = Node(‘D’)
root.childleft.childright = Node(‘E’)
链表
它是具有一系列连接节点的线性数据。每个节点存储数据并显示到下一个节点的路由。它们用来实现撤销功能和动态内存分配。
class LinkedList:
def init(self):
self.head = None
def iter(self):
node = self.head
while node is not None:
yield node
node = node.next
def repr(self):
nodes = []
for node in self:
nodes.append(node.val)
return " -> ".join(nodes)
def add_to_tail(self, node):
if self.head == None:
self.head = node
return
for current_node in self:
最后
🍅 硬核资料:关注即可领取PPT模板、简历模板、行业经典书籍PDF。
🍅 技术互助:技术群大佬指点迷津,你的问题可能不是问题,求资源在群里喊一声。
🍅 面试题库:由技术群里的小伙伴们共同投稿,热乎的大厂面试真题,持续更新中。
🍅 知识体系:含编程语言、算法、大数据生态圈组件(Mysql、Hive、Spark、Flink)、数据仓库、Python、前端等等。
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!