slomilll
slomilll

Reputation: 57

Pointers in LinkedList in Java

I am studying the linked lists,and I'm having a little problem understanding references and pointers in Java (and also have some questions for which I can't find answer on the internet.) Namely,I have a class LinkedList that uses class Node like this:

public class LinkedList {
    public Node head;
    public LinkedList(int data) {
        head = new Node(data);
    }
}

and this is my Node class:

public class Node {
    public int data;
    public Node next;
    public Node(int data2) {
        data = data2;
    }
}

I also have method toStringLL() inside LinkedList which looks like:

public void toStringLL() {
    LinkedList l=this;
    while(l.head.next != null) {
        System.out.print(l.head.data+"->");
        l.head = l.head.next;
    }
    System.out.print(l.head.data);
    System.out.println("");
}

I don't understand why this toStringLL() changes my head of linked list,when I am iterating through it with l.head=l.head.next? Shouldn't my head stay the same?I thought that when I write LinkedList l=this,I can freely iterate through l,without affecting this(or am I wrong?) Now when I use Node n=this.head instead of LinkedList l=this,it works,but I have difficulty figuring out why that works and the previous doesn't.. Can someone explain to me the difference between these two?

Upvotes: 1

Views: 158

Answers (2)

Eran
Eran

Reputation: 393966

I don't understand why this toStringLL() changes my head of linked list,when I am iterating through it with l.head=l.head.next?Shouldn't my head stay the same?

When you make the assignment

LinkedList l = this;

you are not creating a new LinkedList object. You are just defining a references to the existing LinkedList object.

Therefore, l.head = l.head.next does exactly the same as this.head = this.head.next. Both change your original list.

On the other hand, when you write

Node n = this.head

you are not changing the head of your List. You are declaring a variable that initially refers to the head of your List, but when you change that variable to refer to other Nodes of your list, the head variable of your list (this.head) remains unchanged.

Upvotes: 5

J Fabian Meier
J Fabian Meier

Reputation: 35843

When you set

l.head=l.head.next;

you change your head.

Upvotes: 0

Related Questions