数据结构基础入门

 

 

python版本实现代码如下所示:

#定义一个栈Stack()
class Stack:
def __init__(self):
self.stack=[]
def push(self,element):
self.stack.append(element)
def pop(self):
return self.stack.pop()
def get_top(self):
if len(self.stack)>0:
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack)==0
s=Stack()
s.push(1)
s.push(2)
s.push(3)
print(s.pop())
print(s.get_top())

#栈的具体使用:使用栈解决括号匹配问题
def brace_match(s):
match={"}":"{","]":"[",")":"("}
stack=Stack()
for ch in s:
if ch in ["(","{","["]:
stack.push(ch)
else:
if stack.is_empty():
return False
elif stack.get_top() == match[ch]:
stack.pop()
else:
return False
if stack.is_empty():
return True
else:
return False

print(brace_match("(((([[[]]]))))"))

#队列的实现-环形队列
class Q:
def __init__(self,size=100):
self.q=[0 for _ in range(size)]
self.size=size
self.rear=0
self.front=0

def push(self,elment):
if not self.is_filled():
self.rear=(self.rear+1) % self.size
self.q[self.rear]=elment
else:
raise IndexError("Q is filled")
def pop(self):
if not self.is_empty():
self.front=(self.front+1) % self.size
return self.q[self.front]
else:
raise IndexError("Q is empty")
def is_empty(self):
return self.rear==self.front
def is_filled(self):
return (self.rear+1) % self.size==self.front

q=Q(5)
for i in range(4):
q.push(i)
print(q.is_filled())
print(q.pop())
print(q.pop())
print(q.pop())
q.push(4)
print(q.is_filled())

 

posted @ 2020-03-06 19:29  The-Chosen-One  阅读(268)  评论(0编辑  收藏  举报