3

I am implementing singly linked list in Java, and I have a problem. In addition and removal of nodes, many people use temporary node like this:

public Object removeFirst() {
   Node temp = head;
   head = temp.next;
   Object returnData = temp.data;
   temp = null;
   size--;
   return returnData;
}

Why is this temp node necessary? At first glance, I think all I have to do in order to remove first element is to change second element into head node.

So my question is that in java, what does object= object mean? Do 2 objects become exactly same inheriting every fields and methods?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
SoulOfAsia
  • 63
  • 4
  • 3
    I suspect you'd benefit from reading https://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference/32010236#32010236 – Jon Skeet Feb 05 '18 at 11:11
  • Thank you! analogies there helped a lot to get a sesne – SoulOfAsia Feb 05 '18 at 11:16
  • 2
    Please edit the title so it makes more sence. I can't even begin to guess what `class = class?` supposed to mean. – M. Prokhorov Feb 05 '18 at 11:20

1 Answers1

6

temp is not needed. It is used to obtain the data of the removed Node after the head variable is no longer referencing that Node, but that can be done without it:

public Object removeFirst() 
{
    Object returnData = head.data;
    head = head.next;
    size--;
    return returnData;
}
Eran
  • 387,369
  • 54
  • 702
  • 768