一、從開始處刪除
從開始處刪除,通常可以假設結構中至少有一個節點。這個操作返回刪除項。其形式如下:
# 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個節點的鏈表結構中刪除最后一項的過程。
該操作在時間上和內存上都是線性的。
三、從任意位置刪除
從一個鏈表結構中刪除第i個項,具有以下三種情況:
- i<=0,使用刪除第1項的代碼。
- 0<i<n,搜索位於i-1位置的節點,刪除其后面的節點。
- i<=n,刪除最后一個節點。
假設鏈表結構至少有一項。這個模式類似插入節點所使用的模式,因為你必須保證不會超過鏈表結構的末尾。也就是說,必須允許probe指針不會超過鏈表結構的倒數第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): head = Node(count, head) print head.data, head.next,head index = 2 newItem = 100 if index <= 0 or head.next is None: removeItem = head.data head = head.next print removeItem else: probe = head while index > 1 and probe.next.next != None: probe = probe.next index -= 1 removeItem = probe.next.data probe.next = probe.next.next print removeItem
下圖展示了包含4項的鏈表結構中刪除位置2的項的過程。
結束!