Using a list for data storage. The list only expands and never contracts
peek(where) is a little more general than the normal peek() function:
peek() = peek(0) shows the item at the top of the stack
peek(1) shows the item just below the top of the stack
peek(-1) shows the bottom of the stack
peek(-2) shows the the item one above the bottom of the stack
class MyStack:
def __init__(self,store_immediate_list = None):
self.storage = []
self.filled = 0
# if there's anything to store immediately, push all items in that list
if store_immediate_list:
for an_item in store_immediate_list:
self.push(an_item)
def size(self):
return self.filled
def push(self,item):
if self.filled == len(self.storage):
self.storage.append(item)
else:
self.storage[self.filled] = item
self.filled += 1
def pop(self):
if self.filled == 0:
return None
self.filled -= 1
return self.storage[self.filled]
def peek(self,where = 0):
if where >= 0:
if where >= self.filled:
return None
return self.storage[self.filled - 1 - where]
else:
where = -where
if where > self.filled:
return None
return self.storage[where-1]
# Testing
a = MyStack(list(range(1,4)))
print ('size = %d, should be 3' % a.size())
print ('peek() = %d, should be 3' % a.peek())
print ('peek(2)= %d, should be 1' % a.peek(2))
print ('peek(-2) = %d, should be 2' % a.peek(-2))
print ('pop() = %d, should be 3' % a.pop())
a.push(12)
print ('push(12), pop() = %d, should be 12' % a.pop())
a.pop()
print ('pop(), pop() = %d, should be 1' % a.pop())
print ('pop() should be None, is ', a.pop())