C#变量赋值的内存机制解惑:修改current为何影响head?
Hey there! I totally get why this feels confusing at first—reference types can trip up even experienced developers when you're first wrapping your head around them. Let's break this down step by step so it clicks.
Core Concept: Reference Variables Don't Copy Objects
When you write ListNode current = head;, you're not creating a copy of the head node or its properties. Instead, current becomes a second reference variable that points to the exact same memory location as head. Think of them like two different labels stuck on the same box—both labels refer to the same thing, even though they're separate labels.
Let's Walk Through Your Code
Let's break down what's happening in your loop:
while (current != null && current.next != null) { if (current.next.val == current.val) { current.next = current.next.next; } else { current = current.next; } } return head;
When you modify
current.next:
This line doesn't change thecurrentreference itself—it changes a property of the object thatcurrentpoints to. Sinceheadalso points to that same initial node (and the linked chain connected to it), any changes to the nodes'nextproperties will be visible when you accessheadlater.For example: If
currentis pointing to a node with value 1, andcurrent.nextis another 1, settingcurrent.next = current.next.nextrewires the first 1'snextpointer to skip the duplicate. This rewiring is part of the original linked list thatheadpoints to, soheadwill see this change.When you do
current = current.next:
This is the only time you change thecurrentreference itself. Nowcurrentpoints to the next node in the list—but this doesn't affectheadat all.headstill holds its original reference to the first node of the list.
A Simple Analogy
Imagine you and a friend both have a note with the address of your house (this is head and current):
- If your friend goes to your house and replaces your front door (this is modifying
current.next), when you go home, you'll see the new door too—because you're both referring to the same house. - If your friend crosses out your address and writes down your neighbor's address (this is
current = current.next), your note still has your original address—you're not affected by their change.
Why head Reflects the Changes
All the modifications you're making are to the nodes in the linked list structure that head originally points to. The current variable is just a tool to traverse and modify that structure. Since you never change what head points to (you never do head = ...), it still refers to the start of the modified linked list.
内容的提问来源于stack exchange,提问作者Max Kenney

