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,4):
    head = Node(count, head)
    print head.data, head.next,head

removeItem = head.data
head 
= head.next print removeItem

下圖記錄了刪除第1個節點的情況:

該操作使用的時間和記憶體都是常數的,這和陣列上相同的操作有所不同。

二、從末尾刪除

從一個數組的末尾刪除一項(python的pop操作)需要的時間和記憶體都是常數的,除非必須調整陣列的大小。對於單鏈表來說,從末尾刪除的操作假設結構中至少有一個節點。需要考慮如下的兩種情況:

  • 只有一個節點。head指標設定為None。
  • 在最後一個節點之前沒有節點。程式碼搜尋倒數第2個節點並將其next指標設定為None。

在這兩種情況下,程式碼都返回了所刪除的節點所包含的資料項。形式如下:

# 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): head = Node(count, head) print head.data, head.next,head removeItem = head.data if head.next is None: head = Node else: probe = head
while probe.next.next != None: probe = probe.next removeItem = probe.next.data probe.next = None print removeItem

下圖展示了從擁有3個節點的連結串列結構中刪除最後一項的過程。

該操作在時間上和記憶體上都是線性的。

結束!