一.棧結構(stack)
棧類型數據結構相當于一個容器,其特點是先進后出,因此棧具有以下幾個功能:壓棧即入棧,出棧,計算元素個數,返回棧頂元素,判空等操作。
stack.JPG
因此將講個功能命名為:push(),pop(),size(),peek(),is_empty()運用python代碼實現:
#-*-code = utf-8 -*-
class stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self,item):
#壓棧
self.items.append(item)
def pop(self):
''' 彈出或刪除一個元素'''
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
'''返回棧頂元素'''
return self.items[len(self.items)-1]
def delete(self):
for i in range(0,len(self.items)):
self.items.pop()
#del self.items
if __name__ == '__main__':
sta = stack()
for i in range(0,10):
sta.push(i)
print("the size of the stack is :%d"%(sta.size()))
a = [1,2,3,4,5,6]
a.pop()
#pop()本身就是彈出棧頂元素
#加入下標后彈出指定位置元素
print(a)
sta.push(11)
print("the size of the stack is :%d"%(sta.size()))
print(sta.peek())
sta.pop()
print("the size of the stack is :%d"%(sta.size()))
print(sta.is_empty())
sta.delete()
print(sta.is_empty())
print(sta.size())
這種寫法有個問題就是在pop()功能的地方,這里本身pop的功能是在列表中刪除列表的最后一個元素,也可以刪除指定下標位置的元素pop(i),因此為了滿足本次stack的功能我們這里不使用刪除指定下標元素。