0

I am a bit new to Java and one thing is currently bothering me a bit regarding referencing.

I have a method that returns void. I passed in a linked list to this method. There is another linked list variable called noDuplicateLL that references to the same linked list. noDuplicateLL skips nodes in the linked list.

code:

public static void removeDuplicate(LinkedListNode a) {
    LinkedListNode noDuplicateLL = null;
    if (a == null) {
        //return null;
    } else {
        HashMap<Integer, Boolean> duplicateCheck = new HashMap<Integer, Boolean>();
        while (a != null) {
            // check in hashtable O(1)
            if (duplicateCheck.containsKey(a.data)) {
                noDuplicateLL.next = a.next;
            } else {
                noDuplicateLL = a;
                duplicateCheck.put(a.data, true);
            }
            // update
            a = a.next;
        }
    }
}

LinkedListNode a gets iterated through the whole list. LinkedListNode noDuplicateLL stops moving once a reaches null. So once this method is done, both pointers are pointing somewhere else in the list, not the front.

The method below prints on the list from beginning to end.

public static void printLinkedList(LinkedListNode head) {
    while (head != null) {
        System.out.println(head.data);
        head = head.next;
    }
}

My main:

    LinkedListNode LL = LinkedList.randomLinkedList(nodeVal);
    removeDuplicate(LL);
    printLinkedList(LL);

How come the output still prints from beginning to end of the linked list when LL is passed into the method as a? Is it because a simply points to the nodes in the linked list while LL maintains the reference to the front of the linked list?

Liondancer
  • 15,721
  • 51
  • 149
  • 255

1 Answers1

1
LL --> some head node
// invoke method
// LL's value bound to parameter a
a --> some head node
// method executes
a --> head's next
a --> that next's next
...
a --> null
// method exits

LL still points to the original head node.

Is it because a simply points to the nodes in the linked list while LL maintains the reference to the front of the linked list?

Yes. Read this as soon as you can.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724