rudraishere
New member
- Joined
- May 11, 2020
- Messages
- 1
- Programming Experience
- 10+
I was trying to create a "reverse a linked list" solution using C#. Here is the code:
Curiously, when the code in label2 runs, it also updates the newHead object, even though the curr object is reassigned at label1. Why is this happening?
C#:
public class Solution
{
public class LinkedNode
{
public LinkedNode(int value)
{
Value = value;
}
public int Value { get; set; }
public LinkedNode Next { get; set; }
}
public void ReverseLinkedList(LinkedNode head, ref LinkedNode newHead)
{
if (head.Next != null)
{
LinkedNode curr = head;// label1
LinkedNode prev = null;
while (curr.Next != null)
{
prev = curr;
curr = curr.Next;
}
prev.Next = null;
curr.Next = prev; // label2
if (newHead == null)
{
newHead = curr;
}
ReverseLinkedList(head, ref newHead);
}
}
}
Curiously, when the code in label2 runs, it also updates the newHead object, even though the curr object is reassigned at label1. Why is this happening?
Last edited by a moderator: