一.栈的封装
class Stack(object):
"""以list为基础封装栈数据结构"""
def __init__(self):
self.stack = []
def push(self, val):
"""入栈"""
self.stack.append(val)
def pop(self):
"""出栈"""
if self.is_empty():
return 'error'
item = self.stack.pop()
return item
def is_empty(self):
"""判断栈是否为空"""
return len(self.stack) == 0
def top(self):
"""获取栈顶元素"""
if self.is_empty():
return 'error'
return self.stack[-1]
def __len__(self):
"""获取栈元素"""
return len(self.stack)
def __str__(self):
return ",".join([str(i) for i in self.stack])
s = Stack()
s.push(5)
s.push(3)
print(str(s))
二.队列的封装
class Queue(object):
"""以list为基础封装队列数据结构"""
def __init__(self):
self.queue = []
def enqueue(self, val):
"""入队列"""
self.queue.append(val)
def dequeue(self):
"""出队列"""
if self.is_empty():
return 'error'
item = self.queue.pop(0)
return item
def is_empty(self):
"""判断队列是否为空"""
return len(self.queue) == 0
def top(self):
"""获取队头元素"""
if self.is_empty():
return 'error'
return self.queue[0]
def __len__(self):
"""获取队列元素"""
return len(self.queue)
def __str__(self):
return ",".join([str(i) for i in self.queue])
q = Queue()
q.enqueue(5)
q.enqueue(3)
print(str(q))
print(len(q))