Question Method Parameter by reference

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:

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:
If modifying the object referred to by curr is reflected in newHead then obviously they refer to the same object. You may not think they should but they obviously do. It's hard to say exactly why that happens just by reading the code but you don't have to just read the code. You can debug the code and watch the values of your variables as you step through it line by line. You can place a watch on the expression curr == newHead or evaluate it in the Immediate window to see if and when those two variables refer to the same object.
 
Back
Top Bottom