【问题标题】:only print last two value of linked list只打印链表的最后两个值
【发布时间】:2015-02-09 03:52:52
【问题描述】:

这是我的节点类

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

【问题讨论】:

  • 显示实际打印的代码。

标签: java linked-list nodes


【解决方案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);  
        }

    } 
}

【讨论】:

    【解决方案2】:

    你有两个错误。

    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);
    } 
    

    错误已在 cmets 中指出。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2020-01-04
      相关资源
      最近更新 更多