本文實例講述了Python實現(xiàn)數(shù)據(jù)結(jié)構(gòu)線性鏈表(單鏈表)算法。分享給大家供大家參考,具體如下:
成都創(chuàng)新互聯(lián)是一家朝氣蓬勃的網(wǎng)站建設公司。公司專注于為企業(yè)提供信息化建設解決方案。從事網(wǎng)站開發(fā),網(wǎng)站制作,網(wǎng)站設計,網(wǎng)站模板,微信公眾號開發(fā),軟件開發(fā),小程序開發(fā),十余年建站對成都VR全景等多個領域,擁有豐富的網(wǎng)站運維經(jīng)驗。初學python,拿數(shù)據(jù)結(jié)構(gòu)中的線性鏈表存儲結(jié)構(gòu)練練手,理論比較簡單,直接上代碼。
#!/usr/bin/python # -*- coding:utf-8 -*- # Author: Hui # Date: 2017-10-13 # 結(jié)點類, class Node: def __init__(self, data): self.data = data # 數(shù)據(jù)域 self.next = None # 指針域 def get_data(self): return self.data # 鏈表類 class List: def __init__(self, head): self.head = head # 默認初始化頭結(jié)點 def is_empty(self): # 空鏈表判斷 return self.get_len() == 0 def get_len(self): # 返回鏈表長度 length = 0 temp = self.head while temp is not None: length += 1 temp = temp.next return length def append(self, node): # 追加結(jié)點(鏈表尾部追加) temp = self.head while temp.next is not None: temp = temp.next temp.next = node def delete(self, index): # 刪除結(jié)點 if index < 1 or index > self.get_len(): print "給定位置不合理" return if index == 1: self.head = self.head.next return temp = self.head cur_pos = 0 while temp is not None: cur_pos += 1 if cur_pos == index-1: temp.next = temp.next.next temp = temp.next def insert(self, pos, node): # 插入結(jié)點 if pos < 1 or pos > self.get_len(): print "插入結(jié)點位置不合理..." return temp = self.head cur_pos = 0 while temp is not Node: cur_pos += 1 if cur_pos == pos-1: node.next = temp.next temp.next =node break temp = temp.next def reverse(self, head): # 反轉(zhuǎn)鏈表 if head is None and head.next is None: return head pre = head cur = head.next while cur is not None: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre def print_list(self, head): # 打印鏈表 init_data = [] while head is not None: init_data.append(head.get_data()) head = head.next return init_data if __name__ == '__main__': head = Node("head") list = List(head) print '初始化頭結(jié)點:\t', list.print_list(head) for i in range(1, 10): node = Node(i) list.append(node) print '鏈表添加元素:\t', list.print_list(head) print '鏈表是否空:\t', list.is_empty() print '鏈表長度:\t', list.get_len() list.delete(9) print '刪除第9個元素:\t',list.print_list(head) node = Node("insert") list.insert(3, node) print '第3個位置插入‘insert'字符串 :\t', list.print_list(head) head = list.reverse(head) print '鏈表反轉(zhuǎn):', list.print_list(head)
新聞標題:Python實現(xiàn)數(shù)據(jù)結(jié)構(gòu)線性鏈表(單鏈表)算法示例-創(chuàng)新互聯(lián)
瀏覽路徑:http://muchs.cn/article14/dgijde.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設計公司、App設計、外貿(mào)建站、App開發(fā)、網(wǎng)站排名、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容