我正在學習交換節點。問題來自Leetcode:
給定一個鏈表,交換每兩個相鄰節點并回傳它的頭部。您必須在不修改串列節點中的值的情況下解決問題(即,只能更改節點本身。)
現在,顯然我的嘗試不起作用,我很困惑(像往常一樣)為什么temp代碼會更新。
head = [1,2,3,4,5,6]
def swapPairs(self):
temp=self
print("orig %s", (temp))
for x in range(len(self)):
if x%2!=0:
print("temp odd before %s", (temp))
self[x]=temp[x-1]
print("temp odd after %s", (temp))
else:
print("temp even before %s", (temp))
self[x]=temp[x 1]
print("temp even after %s", (temp))
return self
我看到當我列印temp它的值時,它的值正在更新。但它在等式的右邊。
怎么會這樣?
第二個問題是交換節點的實際問題。
奇數元素與前一個偶數元素交換。
請指教。
謝謝
uj5u.com熱心網友回復:
要回答您的直接問題,
temp=self
點temp和self記憶體中的相同位置。對參考的串列的修改self將反映在 中temp,反之亦然。解決方案是創建串列的副本,或者通過執行
temp[:]=self
或者
temp=list(self)
但是,我將包含一個適當的問題的解決方案,因為即使您解決了這個問題,您也需要弄清楚如何對鏈表執行操作,這不一定是一項微不足道的任務。本質上,對于每對節點,您需要跟蹤:
- 對中的第一個節點
- 對中的第二個節點
- 對中第一個節點之前的節點,以便
next可以適當地設定其欄位。
我們遍歷串列,根據需要修改指標:
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
has_head_changed = False
current_node = head
previous = None
while current_node and current_node.next:
next_node = current_node.next
current_node.next = current_node.next.next
next_node.next = current_node
if previous:
previous.next = next_node
if not has_head_changed:
head = next_node
has_head_changed = True
previous = current_node
current_node = current_node.next
return head
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425620.html
