此实现使用链接列表而不是使用内置列表。有没有人使用哪个版本的性能更好?
class Stack:
top = ''
def __init__(self,data=None,next=None):
self.data = data
self.next = next
def pop(self):
if self.top != None:
item = self.top.getvalue()
self.top = self.top.next
return item
else:
return
def push(self,data):
t = Stack(data)
t.next = self.top
self.top = t
def peek(self):
return self.top.getvalue()
def getvalue(self):
return self.data
s = Stack()
s.push('bottom')
s.push('middle')
s.push('top')
popped = s.pop()
print(popped)
top = s.peek()
print(top)
输出:
顶部
中间
答案 0 :(得分:0)
基于内置列表的堆栈类将具有更多更好的性能,例如
class StackEmptyError(Exception):
pass
class ListBasedStack(list):
push = list.append
def pop(self):
try:
return super(ListBasedStack, self).pop()
except IndexError:
raise StackEmptyError
def peek(self):
try:
return self[-1]
except IndexError:
raise StackEmptyError
使用timeit
模块测量执行时间:
>>> import timeit
>>> stmt = '''
s = Stack()
s.push('bottom')
s.push('middle')
s.push('top')
s.peek()
s.pop()'''
# test built-in list stack class
>>> timeit.repeat(stmt, 'from __main__ import ListBasedStack as Stack')
[1.4590871334075928, 1.4085769653320312, 1.3971672058105469]
# test OP stack class
>>> timeit.repeat(stmt, 'from __main__ import Stack')
[5.018421173095703, 4.971158981323242, 4.990453004837036]
基于内置列表的类比链接列表快约3.5倍。
而且,如果您对于为IndexError
操作提出Stack
例外情况并不挑剔,那么它会更快(大约快5倍):
class MinimalistStack(list):
push = list.append
def peek(self):
return self[-1]
>>> timeit.repeat(stmt, 'from __main__ import MinimalistStack as Stack')
[0.9379069805145264, 0.9144589900970459, 0.9160430431365967]