鍊錶相關程式設計題 Python

2021-09-26 22:17:47 字數 2805 閱讀 2196

從尾到頭列印鍊錶

鍊錶中倒數第k個結點

class solution:

def findkthtotail(self, head, k):

# write code here

if not head:

return none

pfast, pslow = head, head

for i in range(k):

if pfast == none:

return none

pfast = pfast.next

while pfast:

pfast = pfast.next

pslow = pslow.next

return pslow

反轉鍊錶

class solution:

# 返回listnode

def reverselist(self, phead):

# write code here

if not phead:

return none

pre = none

while phead:

next_node = phead.next   # 提前儲存當前節點的下一節點

phead.next = pre   # 翻轉,當前節點的下一節點是其上一節點

pre = phead    # 上一節點向後移動

phead = next_node    # 當前節點向後移動

return pre

合併兩個排序的鍊錶

class solution:

# 返回合併後列表

def merge(self, phead1, phead2):

# write code here

if not phead1:

return phead2

if not phead2:

return phead1

mergehead = none

if phead1.val <= phead2.val:

mergehead = phead1

mergehead.next = self.merge(phead1.next, phead2)

elif phead1.val > phead2.val:

mergehead = phead2

mergehead.next = self.merge(phead1, phead2.next)

return mergehead

複雜鍊錶的複製

class solution:

# 返回 randomlistnode

def clone(self, phead):

# write code here

if phead is none:

return none

# copy node set next

cur_node = phead

while cur_node:

next_node = cur_node.next

copy_node = randomlistnode(cur_node.label)

cur_node.next = copy_node

copy_node.next = next_node

cur_node = next_node

# set random

cur_node = phead

while cur_node:

next_node = cur_node.next

if cur_node.random is none:

next_node.random = none

else:

next_node.random = cur_node.random.next

cur_node = next_node.next

# split

new_head = phead.next

cur_node = phead

while cur_node:

next_node = cur_node.next

cur_node.next = next_node.next

if next_node.next is none:

next_node.next = none

else:

next_node.next = next_node.next.next

cur_node = cur_node.next

return new_head

兩個鍊錶的第乙個公共結點

鍊錶中環的入口結點

刪除鍊錶中重複的結點

class solution:

def deleteduplication(self, phead):

# write code here

if not phead:

return none

prenode = listnode(none)

prenode.next = phead

last = prenode

cur = phead

while cur and cur.next:

if cur.val == cur.next.val:

val = cur.val

while cur and cur.val == val:

cur = cur.next

last.next = cur

else:

last = cur

cur = cur.next

return prenode.next

演算法題 鍊錶相關

題目 請編寫乙個函式,使其可以刪除某個鍊錶中給定的 非末尾 節點,你將只被給定要求被刪除的節點。解析 由於只輸入了需要刪除的節點node,因此無法獲取刪除節點node的前乙個節點pre,從而也就無法將前乙個節點pre指向刪除節點的下乙個節點nex 既然無法通過修改指標完成,那麼肯定要修改鍊錶節點的值...

鍊錶相關程式設計練習

合併兩個有序的鍊錶 思路 目的是將兩個有序的鍊錶合併為新的有序列表,我們每次操作的都是要獲取l1指向結點和l2指向結點中,值較小的結點。遞迴 解題 函式返回值 返回l1指向的結點和l2指向的結點中,值較小的結點。並且將從下級函式獲得的返回值,鏈結到當前結點next 結束條件 至少有乙個為空,返回剩下...

刷題筆記 鍊錶相關

輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。分析 初始時,將 pren 指向 nullptr,curn 指向鍊錶首部,提前記錄好鍊錶的下乙個節點。為了反轉鍊錶,要將 curn 的 next 指標指向 pren。class solution return curn 輸入乙個鍊錶,輸出該鍊錶中倒數第k個...