Noam Hacker Noam Hacker - 9 months ago 49
Java Question

References to nodes in Java linked list

I need some help understanding how a method works.

I have a basic

class defined like this:

class Node {
Node next = null;
int data;
public Node(int d){
data = d;

Now I'm looking at how this
method is working. I understand that we are passing through each node iteratively and storing its value in a set. If the value is already in the set, I believe we are setting the previous node's
pointer to skip the current node. Here's the method:

public static Node deleteDuplicates(Node head){
Node n = head;
HashSet<Integer> set = new HashSet<Integer>();
Node previous = null;
while(n != null) {
if (set.contains({
// skip this node =;
else {
previous = n;
n =;

return head;

I'm confused about the variables
. When we set
previous = n;
, isn't that making them reference the same object? If they reference the same object, one change you make to
will be the same in
. So how does the line =;


Answer Source

read these 2 lines together,

previous = n;  
n =;

So, once a node is processed, the pointers for previous and n are moved forward. n is next node after previous, thus previous is set to n, and n is moved to its next node, which is

For the deletion part, hope the diagram below helps

enter image description here