Question

I want to implement a LinkedListremove method that removes items at any specific location but I'm mostly interested in removing an item at the beginning (zeroth place) of the list in this case.

My code works for values of n greater than zero so I wrote an if statement for when n==0 but couldn't understand why it wasn't working until I googled the answer, which to me looked similar to what I had written.

public class LinkedList<E> extends Node<E>{
public LinkedList(){}
public Node<E> head;
//removes node at n and returns contents of removed node; 
public E remove(int n){
    Node<E> current = head; T info;
    if(n==0){info=current.getInfo();
        head=current.getNext();return info;}
    }
}

My initial statement was head=head.getNext() and not head=current.getNext() hence my question. What's the difference between the two?

Are they equivalent but executed differently? Thanks

No correct solution

OTHER TIPS

If the value of head is assigned to current (as it is here), they should be equivalent. Because they are objects, not primitives, assigning one to the other makes them both references to the same object. Because of this, calling head.getNext() and current.getNext() should both return references to the same object.

head (shorthand for this.head) is the object property, while current is a local variable which is only visible inside the code block it'S declared in.

WHen just retreiving the value, there is no difference, so if that really was all you changed, both versions should work.

Modifygin is different however. When changing current, the change won't be reflected outside the block, if the function is finished, current will just be removed. If you change this.head however, you changed the reference stored in the object propert,y, and that change will persist after the function ended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top