0

I have the solution. So I do not need help, but I have a question. This code works:

public void Delete(ref Node n)
{
    n = n.next;
}

LinkedList list = new LinkedList();
list.AddTail(4);
list.AddTail(3);
list.AddTail(2);
list.AddTail(1);
list.AddTail(0);

list.Delete(ref list.head.next.next);

But this code does not:

Node n = list.head.next.next;
list.Delete(ref n);

Why?

EDIT:

public class Node
{
    public int number;
    public Node next;

    public Node(int number, Node next)
    {
        this.number = number;
    }
}
Orvel
  • 297
  • 4
  • 13

1 Answers1

0

When you call

list.Delete(ref list.head.next.next);

You change reference (pointer) to field List.next.

But if you call

list.Delete(ref n);

You change reference (pointer) of local variable.

Just try to inline you code:

list.Delete(ref list.head.next.next);

looks like

list.head.next.next = list.head.next.next.next;

But

Node n = list.head.next.next; 
list.Delete(ref n);

looks like

Node n = list.head.next.next; 
n = n.next;
Alex
  • 172
  • 1
  • 6