简体   繁体   中英

Implementation of add element method to linked list in java

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 ie 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 ?

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
}

如果firstLink在程序开始时初始化为null ,则对add(data)的第一次调用会将firstLink设置为nextnull的新Link。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM