运行列表时出现堆栈溢出错误

时间:2014-09-06 20:50:32

标签: java data-structures

我正在研究数据结构,我必须自己做一个双链表,创建Node和List对象而不是使用Java实现LikedList,每次我尝试添加2时都会出现Stack Overflow错误列表中的元素,我不知道为什么。你能帮我吗?

public class DoubleLinked {
    Node head;
    Node tail;
    int size;

    public DoubleLinked() {
        head = tail = null;
        size = 0;
    }

    public void insertOnHead(int x) {
        Node newNode = new Node();
        newNode.value = x;
        if(head == null) {
            head = newNode;
            size++;
        } else {
            newNode.next = head;
            head.previous = newNode;
            head = newNode;
            size++;
        }
    }

    @Override
    public String toString() {
        return "[Head: " + head + ", Tail: " + tail + ", Size: "
                + size + "]";
    }
}


public class Node {

    int value;
    Node next;
    Node previous;

    @Override
    public String toString() {
        return "Node [Value: " + value + ", Next: " + next + ", Previous: " + previous + "]";
    }
}

它插入第一个元素(5)但不插入第二个元素(6)。

主:

public class DEMain 
{
    public static void main(String[] args)

    {
        DoubleLinked l1 = new DoubleLinked();

        l1.insertOnHead(5);
        l1.insertOnHead(6);
        System.out.println(l1);

    }
}

stacktrace:

Exception in thread "main" java.lang.StackOverflowError at
java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:63) 
at java.lang.StringBuilder.<init>(StringBuilder.java:109) 
at DoblementeEnlazadas.Nodo.toString(Nodo.java:12) 
at java.lang.String.valueOf(String.java:2854) 
at java.lang.StringBuilder.append(StringBuilder.java:128) 
at DoblementeEnlazadas.Nodo.toString(Nodo.java:12) 

1 个答案:

答案 0 :(得分:5)

异常堆栈跟踪会确​​认它,但问题非常明显:

public String toString() {
    return "Node [Value: " + value + ", Next: " + next + ", Previous: " + previous + "]";
}

因此,当您将节点转换为字符串时,您也会转换其两个邻居。这会导致调用它们的toString()方法,这会转换它们的2个邻居,从而导致调用它们的toString()方法,从而转换它们的2个邻居等等。