分别采用有序列表、单向链和双向链实现栈的推入、弹出等功能。
方法一:有序列表的实现
# 直接利用python内置的list实现
class Stack(object):
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def peek(self):
if self.isEmpty():
raise IndexError("peek from empty stack")
return self.stack[-1]
def pop(self):
if self.isEmpty():
raise IndexError("pop from empty stack")
return self.stack.pop()
def isEmpty(self):
return self.stack == []
def __len__(self):
return len(self.stack)
方法二:单链表的实现
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return self.value
class Stack(object):
def __init__(self):
self.head = None
def push(self, value):
node = Node(value)
if self.head is None:
self.head = node
else:
node.next = self.head
self.head = node
def pop(self):
if self.isEmpty():
raise IndexError("pop from empty stack")
else:
node = self.head.value
self.head = self.head.next
return node
def peek(self):
if self.isEmpty():
raise IndexError("peek from empty stack")
else:
return self.head.value
def isEmpty(self):
return self.head is None
def __len__(self):
length = 0
current = self.head
while current:
length += 1
current = current.next
return length
方法三:双链表的实现
class Node(object):
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def __repr__(self):
return self.value
class Stack(object):
def __init__(self):
self.head = None
def push(self, value):
new_node = Node(value)
if self.isEmpty():
self.head = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
def pop(self):
if self.isEmpty():
raise IndexError("pop from empty stack")
else:
current = self.head
if current.next is None:
self.head = None
else:
current.next.prev = None
self.head = current.next
return current.value
def peek(self):
if self.isEmpty():
raise IndexError("peek from empty stack")
else:
return self.head
def __len__(self):
length = 0
current = self.head
while current:
length += 1
current = current.next
return length
def isEmpty(self):
return self.head is None