Reputation: 117046
I am working with a simple link list. I am trying to create a method that will insert an item to the front of my link list.
This Method works:
// Works
public static LinkedListNode AddItemAtFrontWorkingVersion(LinkedListNode node, int value)
{
var newNode = new LinkedListNode(value);
newNode.next = node;
return newNode;
}
Called by:
LinkedListNode a = new LinkedListNode(5);
a = LinkedListNode.AddItemAtFrontWorkingVersion(a, 99);
Now I have a different version which doesn't work and i cant figure out why. The list is an object so it should be on the heap why cant i just set to the new node. When the method returns it is not changed.
Question: Why do I have to return the node why cant I just assign it like I am in AddItemAtEnd?
// Does Not work
public static void AddItemAtFront(LinkedListNode node, int value)
{
var newNode = new LinkedListNode(value);
newNode.next = node;
node = newNode;
}
Called by:
LinkedListNode a = new LinkedListNode(5);
LinkedListNode.AddItemAtFront(a, 99);
Full code:
using System;
namespace DataStructure
{
public class LinkedListNode
{
public int value;
public LinkedListNode next;
public LinkedListNode(int value)
{
this.value = value;
}
public static void AddItemAtEnd(LinkedListNode node, int value) {
var list = node.next;
while (node.next != null)
{
node = node.next;
}
node.next = new LinkedListNode(value);
}
// Does Not work
public static void AddItemAtFront(LinkedListNode node, int value)
{
var newNode = new LinkedListNode(value);
newNode.next = node;
node = newNode;
}
// Works
public static LinkedListNode AddItemAtFrontWorkingVersion(LinkedListNode node, int value)
{
var newNode = new LinkedListNode(value);
newNode.next = node;
return newNode;
}
}
class Program
{
static void Main(string[] args)
{
LinkedListNode a = new LinkedListNode(5);
LinkedListNode.AddItemAtFront(a, 99);
a = LinkedListNode.AddItemAtFrontWorkingVersion(a, 99);
LinkedListNode.AddItemAtEnd(a, 9);
LinkedListNode.AddItemAtEnd(a, 10);
LinkedListNode.AddItemAtEnd(a, 11);
LinkedListNode.AddItemAtEnd(a, 12);
LinkedListNode.AddItemAtFront(a, 99);
a = LinkedListNode.AddItemAtFrontWorkingVersion(a, 99);
Console.Read();
}
}
}
Upvotes: 0
Views: 1002
Reputation: 18265
You are passing your LinkedListNode
by value. For your second version to be working you have to pass it by reference.
public static void AddItemAtFront(ref LinkedListNode node, int value)
{
var newNode = new LinkedListNode(value);
newNode.next = node;
node = newNode;
}
More details may be found inside the documentation: Passing Reference-Type Parameters .
Upvotes: 1