你可以使用類似這樣(警告:這是一個天真的實現 - 它不會對傳入的參數進行檢查):
class Stack(object):
def __init__(self):
self._stack = [] # Allocate an empty list
def push(self, ele):
self._stack += [ele] # Use list concatenation to emulate the `push` operation
def pop(self):
last = self._stack[-1:] # Return the last element of the list (also works for empty lists)
self._stack = self.stack[0:-1] # Copy the elements from the beginning of the list to the last element of the list
return last # return the last element
# All stacks should have the `size` function to determine how many elements are
# in the stack:
def size(self):
return len(self._stack)
# Occasionally you'll want to see the contents of the stack, so we have to
# implement the `__str__` magic method:
def __str__(self):
return '[%s]' % ','.join(map(str, self._stack))
注意:此方法不使用任何的list
方法爲append
和pop
。
例:
s = Stack()
# fill the stack with values:
for i in xrange(10):
s.push(i+1)
print s # Outputs: [1,2,3,4,5,6,7,8,9,10]
s.pop()
s.pop()
print s # Outputs: [1,2,3,4,5,6,7,8]
'堆棧[LEN(棧)]'永遠如果'stack'是'list' –