只打印链表的最后两个值

时间:2015-02-09 03:52:52

标签: java linked-list nodes

这是我的Node类

public class listNode {
String data;
listNode next;

     public listNode(String data, listNode next) {
        this.data = data;
        this.next = next;
     }       

     public String toString(){
        return data;
     }
}

她是我的List类

public class List {
listNode head;

    public List(){
        head = null;
    }

    public void addLast(String target){
        if(head == null){
            head = new listNode(target,head);
        }
        while(head.next != null){
            head = head.next;
        }
        head.next = new listNode(target,null);
    } 
}

打印方法:

public void print(){
    while(head != null){
        System.out.println(head.toString());
        head = head.next;
    }
}

当我在main函数中使用这个方法时,它总是只打印链表的最后两个值,我很困惑。

示例:

l1.addLast("a");
l1.addLast("b");
l1.addLast("c");

只打印

b,c

2 个答案:

答案 0 :(得分:1)

以下代码不正确。您不应该更改头部对象。使用其他对象。

while(head.next != null){
            head = head.next;
}

应该是这样的:

class List {
listNode head;

    public List(){
        head = null;
    }

    public void addLast(String target){
        if(head == null){
            head = new listNode(target,head);
        }
        else {
            listNode last = head;
            while(last.next != null){
                last = last.next;
            }
            last.next = new listNode(target,null);  
        }

    } 
}

答案 1 :(得分:0)

你有两个错误。

public void addLast(String target){
    if(head == null){
        head = new listNode(target,head);
        return; // Mistake 1 - you need to return here - nothing more is needed. 
        // If you don't return. addLast will create 2 listNode's for the first entry.
    }

    listNode h = head; // Mistake 2 - Use a temp instead of head. head will 
                  //no longer point to the start otherwise.

    while(h.next != null)
    {
        h = h.next;
    }
    h.next = new listNode(target,null);
} 

评论中指出了错误。

第一个错误并不严重。第二个是。