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;
    }
}
14
  • What error does it give? Commented Feb 9, 2016 at 12:04
  • in what way doesn't it work? Commented Feb 9, 2016 at 12:06
  • Doesn't give any errors. It just doesn't do anything. Commented Feb 9, 2016 at 12:08
  • What LinkedList are you using? Commented Feb 9, 2016 at 12:09
  • 1
    I think it's not working because in the first case you are changing the next property of list.head.next but in the second case you are just changing the node that your local variable n is referencing. Commented Feb 9, 2016 at 12:23

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.