python 数据结构 list和链表实现栈的三种方法
2020-12-24 21:27
标签:size mamicode class item loading color rom 元素 empty list实现, 头插带头结点的单链表实现链栈,两个队列实现栈 运行结果: python 数据结构 list和链表实现栈的三种方法 标签:size mamicode class item loading color rom 元素 empty 原文地址:https://www.cnblogs.com/liuchaodada/p/13209841.htmlMAX_SIZE = 100
class MyStack1(object):
"""模拟栈"""
def __init__(self):
self.items = []
self.size = 0
def is_empty(self):
"""判断是否为空"""
return self.size == 0
def size(self):
"""返回栈的大小"""
return self.size
def push(self, item):
"""压栈(加入元素)"""
self.items.append(item)
self.size += 1
def pop(self):
"""弹栈(弹出元素)"""
if self.size and self.size >= 0:
self.size -= 1
return self.items.pop()
else:
print("栈已经为空")
return None
def peek(self):
if not self.is_empty():
return self.items[self.size-1]
else:
return None
def __str__(self):
return str(self.items)
class MyStack2(object):
"""模拟栈"""
def __init__(self):
self.items = []
self.size = 0
def is_empty(self):
"""判断是否为空"""
return self.size == 0
def size(self):
"""返回栈的大小"""
if self.size MAX_SIZE:
return self.size
def push(self, item):
"""压栈(加入元素)"""
if self.size MAX_SIZE:
self.items.insert(0, item)
self.size += 1
def pop(self):
"""弹栈(弹出元素)"""
if self.size > 0 and self.size MAX_SIZE:
self.size -= 1
return self.items.pop(0)
else:
print("栈已经为空")
return None
def peek(self):
"""返回栈顶元素"""
if not self.is_empty():
return self.items[0]
else:
return None
def __str__(self):
return str(self.items)
class Node():
def __init__(self, data, next=None):
self.data = data
self.next = next
def __repr__(self):
return str(self.data)
class NodeStack():
def __init__(self):
self.node = Node(None)
self.head = self.node
self.size = 0
def is_empty(self):
return self.size == 0
def get_size(self):
return self.size
def push(self, data):
node = Node(data)
node.next = self.head.next
self.head.next = node
self.size += 1
def pop(self):
if not self.is_empty():
current = self.head.next
if self.get_size() == 1:
self.head.next = None
else:
self.head.next = self.head.next.next
self.size -= 1
return current.data
else:
raise IndexError(‘pop from a empty stack‘)
def peek(self):
if not self.is_empty():
return self.head.next.data
else:
raise IndexError(‘stack is empty‘)
def __repr__(self):
stack_list = []
current = self.head
while current.next is not None:
stack_list.append(current.next.data)
current = current.next
return str(stack_list)
__str__ = __repr__
def test(obj):
i = obj()
for x in range(0,6):
i.push(x)
print(i)
i.pop()
print(i, i.peek(), i.size)
if __name__ == "__main__":
test(MyStack1)
test(MyStack2)
test(NodeStack)
上一篇:Python虚拟环境
文章标题:python 数据结构 list和链表实现栈的三种方法
文章链接:http://soscw.com/index.php/essay/38005.html