18 刪除鍊錶的節點

2021-09-29 14:40:21 字數 2265 閱讀 7955

class

node

(object):

''' 節點類

'''def__init__

(self, data)

: self.num = data

self.

next

=none

class

deletenode

(object):

''' 實現刪除指定節點功能

'''defdelete_node

(self, head, delnode)

:if head ==

none

or delnode ==

none

:return

if head == delnode and delnode.

next

isnone

:# 頭節點

head.num =

none

if delnode.

next

==none

:# 尾節點

while head:

if head.

next

== delnode:

head.

next

=none

head =head.

next

else

:# 中間節點

delnode.num = delnode.

next

.num

delnode.

next

= delnode.

next

.next

# 刪除重複節點

defdeleteduplication

(self, head)

:if head is

none

:return

while head and head.

next

isnot

none

:if head.num == head.

next

.num:

head.

next

= head.

next

.next

head = head.

next

class

printnode()

:'''

輸出指定節點為起始節點的鍊錶

'''defprint_node

(self, node)

: res_list =

while node:

str(node.num)

) node = node.

next

print

('->'

.join(res_list)

)if __name__ ==

'__main__'

: node1 = node(90)

# node2 = node(90)

# node3 = node(77)

# node4 = node(77)

# node5 = node(23)

# node1.next = node2

# node1.next.next = node3

# node1.next.next.next = node4

# node1.next.next.next.next = node5

# 原鍊錶節點

print

('init single linknode is:'

) printnode = printnode(

) printnode.print_node(node1)

# 刪除鍊錶中某個節點

delete = deletenode(

)# delete.delete_node(node1, node3)

# print('after delete node,the single linknode is:')

# printnode.print_node(node1)

# 刪除重複節點

delete.deleteduplication(node1)

print

('after delete duplicationnode,the single linknode is:'

) printnode.print_node(node1)

18 刪除鍊錶節點

給定單向鍊錶的頭指標和乙個要刪除的節點的值,定義乙個函式刪除該節點。返回刪除後的鍊錶的頭節點。注意 此題對比原題有改動 示例 1 輸入 head 4,5,1,9 val 5 輸出 4,1,9 解釋 給定你鍊錶中值為 5 的第二個節點,那麼在呼叫了你的函式之後,該鍊錶應變為 4 1 9.示例 2 輸入...

18 刪除鍊錶的節點

在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 1.首先新增乙個頭節點,以方便碰到第乙個,第二個節點就相同的情況 2.設定 pre last 指標,pre指標指向當前確定不重複的那個節點,而l...

JZ 18 刪除鍊錶的節點(鍊錶)

設當前節點指標 cur curcu r 和前驅節點指標 pre prepr e,遍歷鍊錶找到目標節點後執行 pre nex t cu r.ne xtpre.next cur.next pre.ne xt c ur.n ext 即可刪除 cur curcu r 節點 演算法流程 definition ...