0

So this is the code

void add(String data) {
    Link newLink = new Link(data);
    newLink.next = firstLink;
    firstLink = newLink;
}

If we have only one element firstLink.next will point itself i.e firsLink (because of newLink.next = firstLink;) so it will be not null. and if we have print method like this:

void print() {
    Link currentLink = firstLink;
    while (currentLink != null) {
        System.out.println(currentLink.data);
        currentLink = currentLink.next;
    }
}

this should be a infinite loop, but in fact its not true when I start it in eclipse. My question is why ?

2 Answers 2

1

If you have only one element, then firstLink was null when you added that first element.

That means that your add() method goes like this:

void add(String data) {
    Link newLink = new Link(data);    // create new link
    newLink.next = firstLink;         // set newLink.next = null
    firstLink = newLink;              // make newLink the first link
}
Sign up to request clarification or add additional context in comments.

Comments

1

If firstLink is initialized to null at the start of the program, then the first call to add(data) will set firstLink to a new Link who's next is null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.