數據結構:鏈表(三)
阿新 • • 發佈:2018-09-25
尾插法 .com 鏈表 inf fin 數據 code com python
一、鏈表基礎
1、什麽是鏈表?
鏈表中每一個元素都是一個對象,每個對象稱為一個節點,包含有數據域key和指向下一個節點的指針next。通過各個節點之間的相互連接,最終串聯成一個鏈表。
2、節點定義
class Node(object): def __init__(self, data): self.data = data self.next = None a = Node(5) b = Node(4) c = Node(3) a.next = b b.next = c print(a.next.data)
打印結果:
"D:\Program Files\Python35\python3.exe" E:/test/linklist.py 4 Process finished with exit code 0
3、頭結點
二、鏈表的操作
1、鏈表的遍歷
1、圖形
2、代碼
def print_linklist(head): node =head while node: print(node.data) node = node.next
2、鏈表節點的插入
1、頭插法
class Node(object): def __init__(self, data): self.data = data self.next = None def create_linklist(li): head = None for num in li: node = Node(num) node.next = head head = node return head
結果
"D:\Program Files\Python35\python3.exe" E:test/linklist.py 6 5 4 3 2 1 Process finished with exit code 0
2、尾插法
class Node(object): def __init__(self, data): self.data = data self.next = None def create_linklist(li): head = None for num in li: node = Node(num) node.next = head head = node return head def create_linklist_tail(li): head = None if not li: return head head = Node(li[0]) tail = head for num in li[1:]: node = Node(num) tail.next = node tail = node return head def print_linklist(head): node =head while node: print(node.data) node = node.next linklist = create_linklist_tail([1,2,3,4,5,6]) print_linklist(linklist)
輸出:
"D:\Program Files\Python35\python3.exe" E:/test/linklist.py 1 2 3 4 5 6 Process finished with exit code 0
3、鏈表節點的刪除
三、雙鏈表的操作
1、鏈表節點的插入
2、鏈表節點的刪除
四、鏈表分析
數據結構:鏈表(三)