2017-03-09 46 views
0

我从头开始实现我自己的java.util.linkedlist,所以我没有使用任何java.util.linkedlist功能。这就是说,我目前正在尝试创建我自己的toString方法。这是我的节点类我的链表的toString()方法只打印第一个元素

private static class Node<T>{ 

    private T data; 
    private Node<T> next; 

    public Node(T d){ 
    next= null; 
    data = d; 
    } 

    public Node(T d, Node<T> n){ 
    data = d; 
    next = n; 
    } 

    public T getData(){ 
    return data; 
    } 

    public void setData(T d){ 
    data = d; 
    } 

    public Node<T> getNext(){ 
    return next; 
    } 

    public void setNext(Node<T> n){ 
    next = n; 
    } 
} 

,这是我listclass

private Node<T> start; 
    private int size; 
    public ListNoOrder() { 
    start = null; 
    size = 0; 
} 

public void add(T newElt) { 

    Node<T> temp = new Node<T>(newElt); 
    Node<T> current = start; 

    try{ if (newElt==(null));} 
    catch (Exception illegalArgumentException){ 
    throw new IllegalArgumentException();} 

    if (start == null){ 
    start = new Node<T>(newElt, null); 
    } 

    if(current != null){ 
    while (current.next != null){ 
     current.setNext(temp); 
    } 
    } 
    size++; 
} 

public int length() { 
    return size;} 

,我的toString方法至今

public String toString() { 
    String toPrint = ""; 
    Node <T> current = start; 

    while (current != null){ 
    toPrint += current.getData(); 
    if (current.next != null) 
     toPrint += " ,"; 
    current = current.getNext(); 
    } 
return toPrint; 
} 

当我测试只打印的第一个元素的方法名单。

mockList = 7,8,15,62,38,3 whatItsPrinting = 7,

我已经挣扎小时。

+2

添加您的列表的初始化代码(添加元素并调用toString方法的位置)。另外**哪里是toString方法定义**?它似乎可以访问私人'next'节点字段? –

+0

东西告诉我'start'实际上是你链中的最后一个节点 – AxelH

+0

你是什么意思,toString是在哪里定义的? @ m.antkowicz – rarayo55

回答

2

在你add方法,你在这里开始

start = new Node<T>(newElt, null); 

设置只是start可变的,但你永远不设置下一个节点,因为startnext所以下面的条件是不正确的

if(current != null){ 
    while (current.next != null){ // this one! 
     current.setNext(temp); 
    } 
} 

即使这种情况是真的,它也不会真的起作用 - 你需要做的是获得last节点(节点没有next并且只设置它的next)。类似于

if(current != null) { 
    while(current.getNext() != null) { 
     current = current.getNext(); 
    } 
    current.setNext(new Node<T>(newElt)); 
} 
else { 
    current = new Node<T>(newElt, null); // because current is start 
} 
+0

ohhh我明白了......那么我将如何设置下一个节点呢? – rarayo55

+0

看看我的编辑 –

+0

谢谢谢谢谢谢谢...我刚刚试图抓住它的数据结构!谢谢。 @ m.antkowicz – rarayo55

相关问题