您好,登錄后才能下訂單哦!
本文實例講述了Python實現數據結構線性鏈表(單鏈表)算法。分享給大家供大家參考,具體如下:
初學python,拿數據結構中的線性鏈表存儲結構練練手,理論比較簡單,直接上代碼。
#!/usr/bin/python # -*- coding:utf-8 -*- # Author: Hui # Date: 2017-10-13 # 結點類, class Node: def __init__(self, data): self.data = data # 數據域 self.next = None # 指針域 def get_data(self): return self.data # 鏈表類 class List: def __init__(self, head): self.head = head # 默認初始化頭結點 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): # 追加結點(鏈表尾部追加) temp = self.head while temp.next is not None: temp = temp.next temp.next = node def delete(self, index): # 刪除結點 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): # 插入結點 if pos < 1 or pos > self.get_len(): print "插入結點位置不合理..." 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): # 反轉鏈表 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 '初始化頭結點:\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 '鏈表反轉:', list.print_list(head)
執行結果:
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python加密解密算法與技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。