我無法完全理解 Leetcode 上第 19 個問題的解決方案。
那么,當我們創建快速和慢速時 - 我們創建了頭部鏈接?我可以判斷是的。但是然后我們快速迭代 - 為什么它不改變頭部?我的意思是在我們用 fast.next 替換 fast 的每一步?所以不知何故它不會影響頭部和緩慢。
然后我們用slow.next.next替換slow.next,它會影響head。
您能否描述一下它如何不替換第一部分中的任何內容并替換第二部分。
var removeNthFromEnd = function(head, n) {
let fast = head, slow = head
for (let i = 0; i < n; i ) fast = fast.next // why it doesn’t change head and slow?
if (!fast) return head.next
while (fast.next) fast = fast.next, slow = slow.next
slow.next = slow.next.next // why it change head?
return head
};
uj5u.com熱心網友回復:
為變數賦值不會改變物件。
將某些內容分配給屬性將改變您正在設定其屬性的物件。
在您的情況下,fast是一個變數,因此為它分配一些東西,例如fast.next,永遠不會改變物件。它只是改變了fast所參考的內容。
另一方面,slow.next是財產。將某些內容分配給該屬性將改變slow參考的物件。
讓我們想象一下是什么fast = fast.next。讓我們假設fast是 3 串列中的第二個節點:
前:
head fast
↓ ↓
┌───────────┐ ┌───────────┐ ┌───────────┐
│ data: B │ │ data: G │ │ data: D │
│ next: ──────> │ next: ──────> │ next: null│
└───────────┘ └───────────┘ └───────────┘
后:
head fast
↓ ↓
┌───────────┐ ┌───────────┐ ┌───────────┐
│ data: B │ │ data: G │ │ data: D │
│ next: ──────> │ next: ──────> │ next: null│
└───────────┘ └───────────┘ └───────────┘
現在看看是什么slow.next = slow.next.next。讓我們假設slow參考第一個節點:
前:
slow
head
↓
┌───────────┐ ┌───────────┐ ┌───────────┐
│ data: B │ │ data: G │ │ data: D │
│ next: ──────> │ next: ──────> │ next: null│
└───────────┘ └───────────┘ └───────────┘
后:
slow
head
↓
┌───────────┐ ┌───────────┐ ┌───────────┐
│ data: B │ │ data: G │ │ data: D │
│ next: ─────┐ │ next: ──────> │ next: null│
└───────────┘│ └───────────┘┌> └───────────┘
└───────────────┘
uj5u.com熱心網友回復:
當你這樣做時fast = fast.next,你正在改變一個參考變數。fast現在指向串列中的下一項。
當您這樣做時,slow.next = slow.next.next您正在更改slow指向的物件的屬性。
事實上,在這個例子中,head永遠不會改變,并且總是指向串列中的第一個元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374300.html
標籤:javascript 算法 链表 单链表
上一篇:Python平分:值的搜索范圍
