基於Python和C 實現刪除鍊錶的節點

2022-09-26 18:45:17 字數 1139 閱讀 1553

給定單向鍊錶的頭指標和乙個要刪除的節點的值,定義乙個函式刪除該節點。

返回刪除後的鍊錶的頭節點。

示例 1:

輸入: head = [4,5,1,9], val = 5

輸出: [4,1,9]

解釋: 給定你鍊錶中值為 5 的第二個節點,那麼在呼叫了你的函式之後,該鍊錶應變為 4 -> 1 -> 9.

示例 2:

輸入: head = [4,5,1,9], val = 1

輸出: [4,5,9]

解釋: 給定你鍊錶中值為 1 的第三個節點,那麼在呼叫了你的函式之後,該鍊錶應變為 4 -> 5 -> 9.

思路:建立乙個空節點作為哨兵節點,可以把首尾等特殊情況一般化,且方便返回結果,使用雙指標將更加方便操作鍊錶。

python解法:

class listnode:

def __init__(self, x):

程式設計客棧self.val = x

self.next = none

class solution:

def deletenode(self, head: listnode, val: int) -> listnode:

temphead = listnode(none) # 構建哨兵節點

temphead.next = head

preptr = temphead # 使用雙指標

postptr = head

while postptr:

if postptr.val == val:

preptr.next = postptr.next

break

preptr = preptr.next

postptr = postptr.next

return temphead.next

c++解法:

struct listnode

};class solution

postptr = postptr->next;

preptr = preptr->next;

}return temphead->next;

}};本文標題: 基於python和c++實現刪除鍊錶的節點

本文位址: /jiaoben/python/324664.html

2021 2 1基於Python實現鍊錶

2021 2 1 2.雜記 參考部落格 1.1節點類class node data 節點儲存的資料 next 儲存下乙個節點物件 def init self,data,pnext none self.data data self.next pnext def repr self 用來定義node的字...

C 編寫鍊錶實現插入和刪除等操作

問題描述 編寫鍊錶實現插入和刪除等操作 根據所給主函式以及輸入輸出格式完整 樣例輸入輸出格式 請輸入學生姓名 zhang wang lizhao sunqian 學生資訊為 2018001 li 2018002 wang 2018003 zhang 2018004 zhao 2018005 sun ...

c 實現鍊錶建立 插入 刪除

使用類模板設計的鍊錶建立 插入 刪除操作。類模板不懂的,可以看下我的template簡單介紹 建立鍊錶實際就是將struct結構體或者class類物件連線在一起 鍊錶插入如圖示 使用的是頭插法 鍊錶刪除操作 上 include include include include using namesp...