链接列表不能用Java打印

时间:2013-06-03 03:13:15

标签: java linked-list

所以基本上我正在创建一个循环链表,当我尝试打印出我的代码时,没有任何内容在Eclipse的控制台上打印出来。我希望所有6个数字都显示在控制台上。如果可以,请帮助我。非常感谢!

public class CircularLinkedList 
{
    public Node head;
    public Node tail;

    public CircularLinkedList()
    {
        head =null;
        tail =null;
    }

    public void insert(int v)
    {   
        if( head == null)
        {
            head = new Node(v, null);
            tail = head;    
        }
        else 
        {   
            Node newNode = new Node(v,head); 
            tail.setNextNode(newNode); 
            tail = newNode;
        }
    }

    public String toString()
    {
        if( head == null)
        {
            System.out.println("The list is empty");
        }
        Node newTemp = head;
        String result = "";
        while(newTemp != head)
        {
            result += newTemp.toString();
            newTemp = newTemp.getNextNode();
        }
        return result;
    }

    public static void main(String[] args)
    {
        CircularLinkedList a = new CircularLinkedList();

        a.insert(1);
        a.insert(2);
        a.insert(3);
        a.insert(4);
        a.insert(5);
        a.insert(6);
        System.out.println(a.toString());
    }
}

3 个答案:

答案 0 :(得分:3)

Node newTemp = head;
while(newTemp != head)

您认为这会发生什么? (你在开始循环之前忘了推进一次newTemp,或者把它做成一个do ... while循环,而不是一会儿)

答案 1 :(得分:0)

您需要检查while循环中newTemp是否为空

public String toString() {
    if (head == null) {
        return "";
    }

    String result = "";

    Node temp = head;

    do {
        result += temp.toString();

        temp = temp.getNextNode();

    } while (head != tail && temp != head);
    return result;
}

测试

CircularLinkedList a = new CircularLinkedList();
System.out.println(a.toString());
a.insert(1);
a.insert(2);
a.insert(3);
System.out.println(a.toString());
a.insert(4);
a.insert(5);
a.insert(6);
System.out.println(a.toString());

结果

<empty string>
{ "value": 1}{ "value": 2}{ "value": 3}
{ "value": 1}{ "value": 2}{ "value": 3}{ "value": 4}{ "value": 5}{ "value": 6}

答案 2 :(得分:-1)

您没有前进到下一个节点,因此您的while循环永远不会进入。此外,您的newTemp != head行可能无法正常工作您可能希望在Node类中存储一些额外信息并覆盖.equals()方法以确保此步骤有效。

public String toString()
{
    if( head == null)
    {
        System.out.println("The list is empty");
    }
    Node newTemp = head;
    String result = newTemp.toString(); //Advance to the next node.
    newTemp = newTemp.getNextNode();
    while(newTemp != head) //The root cause of your problem.
    {
        result += newTemp.toString();
        newTemp = newTemp.getNextNode();
    }
    return result;
}