1. 程式人生 > 實用技巧 >單鏈表操作之插入

單鏈表操作之插入

一、在開始處插入

連結串列結構存在優於線性操作的幾種操作。再某些情況下,這些操作使得連結串列結構比陣列更加合適。第一種情況就是在結構的開始處插入一項。如下:

# coding: utf-8
class Node(object):
    def __init__(self, data, next=None):
        self.data = data
        self.next = next


head = None

for count in range(1,6):
    head = Node(count, head)
    print head.data, head.next,head

newItem 
= 100 head = Node(newItem, head)

下圖記錄了這個操作的兩種情況。在第一種情況下,head指標是None,因此向結構中插入了第1項。第2種情況下,將第2項插入到了同一結構的開頭處。

注意第2種情況,不需要複製資料並向下移動,並且不需要額外的記憶體。這意味著,在一個連結串列結構的開始處插入資料,時間和記憶體都是常數,這與陣列的響應操作有所不同。

二、在行尾插入

在一個數組的行尾插入一項(python的oppend操作)需要的時間和記憶體都是常數,除非必須調整陣列大小。對於單鏈表來說,在行尾插入一項必須考慮如下兩種情況:

  • head指標為None,此時,將head指標設定為新的節點。
  • head指標不為None,此時,程式碼將搜尋最後一個節點,並將其next指標指向新的節點。

第2種情況又回到遍歷模式。其形式如下:

# coding: utf-8
class Node(object):
    def __init__(self, data, next=None):
        self.data = data
        self.next = next
        
head = None

for count in range(1,4):  # 為了儘量減少下圖的步驟,此處建立有3個節點的單鏈表
    head = Node(count, head)
    print head.data, head.next,head
        
newItem 
= 100 newNode = Node(newItem) if head is None: head = newNode else: probe = head while probe.next != None: probe = probe.next probe.next = newNode while head.next: head = head.next print head.data

這樣就在head連結串列末尾插入一個新的連結。該操作在時間上是線性的,在空間是是常數的。

結束!