python學習筆記01--鏈表的實現__python

來源:互聯網
上載者:User

    在C語言中,我們通常通過“指標+結構體”來實現鏈表,但是在python中並沒有指標,所以我們必須考慮其它 的方法。在這裡,我們通過定義節點類node,並通過類的嵌套引用來實現鏈表。node類的定義就像鏈表中的節點一樣,包含兩個對象,節點的值(data)和表示指向下一個節點的next。在這裡我們通過節點的next對象再次引用類node來實現next指向下一個節點的目標,這樣不斷嵌套應用,鏈表也就實現了。代碼如下:

__author__ = 'jiangzhiheng'#coding=utf-8import copyclass node():                             #定義一個節點類    def __init__(self,val,p=0):        self.data = val        self.next = pclass linklist():    def __init__(self):        self.head = 0    def initlist(self,data):        self.head = node(data[0])        p = self.head        for i in data[1:]:            p.next = node(i)            p = p.next    def getlength(self):       #獲得鏈表元素的個數        p = self.head        length = 0        while p!=0:            length+=1            p = p.next        return length    def insert(self,item,index):        if index>self.getlength() or index<=0:            print('please enter a valid index')            return        p = self.head        q = node(item)        while (index-1)!=0:        #在第index後面插入對象item            index=index-1            p = p.next        post = copy.deepcopy(p.next)        p.next = q        q.next = post    def getitem(self,index):        if index>self.getlength() or index<=0:            print('please enter a valid index')            return        p = self.head        while (index-1)!=0:            index=index-1            p = p.next        return p.data         #返回鏈表第index個對象的值    def remove(self,index):        if index>self.getlength() or index<=0:            print('please enter a valid index')            return        p = self.head        if index == 1:            self.head = p.next            return        while (index-2)!=0:           #移除鏈表中的第index對象            index=index-1            p = p.next        p.next = p.next.next    def search(self,item):      #在鏈表中搜尋對象item        p = self.head        i = 1        while p!=0:           if p.data == item:               return i           i+=1           p = p.nextl = linklist()l.initlist(range(7))print(l.getlength())l.insert(10,5)print(l.getitem(6))l.remove(5)print(l.search(5))i = 1while i<l.getlength():    print(l.getitem(i),end=',')    i+=1

結果


    在這裡我們需要注意的是python中的‘=’符號與C語言中的‘=’區別,C語言的等號表示賦值,而python中的等號嚴格意義上並不是賦值,而只是引用或者參照



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.