(一) python 實(shí)現(xiàn)數(shù)據(jù)結(jié)構(gòu)之棧(stack)篇

一.棧結(jié)構(gòu)(stack)

棧類型數(shù)據(jù)結(jié)構(gòu)相當(dāng)于一個(gè)容器,其特點(diǎn)是先進(jìn)后出,因此棧具有以下幾個(gè)功能:壓棧即入棧,出棧,計(jì)算元素個(gè)數(shù),返回棧頂元素,判空等操作。

stack.JPG

因此將講個(gè)功能命名為:push(),pop(),size(),peek(),is_empty()運(yùn)用python代碼實(shí)現(xiàn):

#-*-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):
                ''' 彈出或刪除一個(gè)元素'''
              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()本身就是彈出棧頂元素
        #加入下標(biāo)后彈出指定位置元素
        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())

這種寫法有個(gè)問題就是在pop()功能的地方,這里本身pop的功能是在列表中刪除列表的最后一個(gè)元素,也可以刪除指定下標(biāo)位置的元素pop(i),因此為了滿足本次stack的功能我們這里不使用刪除指定下標(biāo)元素。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容