1. 題目
題目一:在O(1)時間內刪除鏈表節點。
給定單向鏈表的頭指針和一個節點指針,定義一個函數在O(1)時間內刪除該節點。鏈表節點與函數的定義如下:
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
}
void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted);
python實現的節點如下:
class ListNode:
def __init__(self, value, next=None):
self.value = value
self.next = next
2. 解題思路
通常而言,要刪除鏈表中的某個節點,需要做的是:根據head節點進行遍歷,將需刪除的節點的前一個節點的next指向需刪除的節點的下一個節點即可。
# 要刪除的節點爲cur,前一個節點是pre
pre.next = cur.next
但是,只要遍歷鏈表,則不可能在O(1)內刪除cur節點。
牛逼的來了,用cur.next這個節點覆蓋掉cur節點就刪除了cur了。
3. 代碼實現
class Solution:
def deleteNode(self, head, cur):
"""
head 爲頭節點,cur爲要刪除的節點
"""
if not head or not cur: # 節點是否存在
return
if cur.next: # 要刪除的節點不爲尾節點
cur.value = cur.next.value
cur.next = cur.next.next
elif head == cur:
head = None
else: # 要刪除的節點是尾節點
temp = head
while temp.next != cur:
temp = temp.next
temp.next = None
在這裏,O(1)是平均時間複雜度。
4. 總結
其實,本題只要有了用後一個節點覆蓋當前節點
等價於刪除當前節點
這個思想就行了。
5. 參考文獻
[1] 劍指offer叢書