为什么这个JAVA代码(DoublyLinkedList)是错误的,stackOverflow

时间:2020-03-10 13:58:48

标签: java doubly-linked-list

我不知道为什么它会堆栈溢出

错误消息是这个

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.AbstractStringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.<init>(Unknown Source)
    at linkedList.Node.toString(DoublyLinkedList.java:15)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)

然后一遍又一遍地重复相同的消息

这是我第一次遇到此错误,所以请让我知道为什么会发生此错误。

这是为了制作双向链表。

当我评论//tail.next = newOne;或//newOne.prev = tail;

有效

谢谢。

class Node{
    String val;
    Node next;
    Node prev;

    public Node(String val){
        this.val = val;
        this.next = null;
        this.prev = null;
    }

    @Override
    public String toString() {
        return "Node [val=" + val + ", next=" + next + ", prev=" + prev + "]";
    }

}

public class DoublyLinkedList {
    Node head;
    Node tail;
    int length;
    LinkedList<Integer> aa = new LinkedList<>();


    public DoublyLinkedList() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    public static void main(String[] args) {
        DoublyLinkedList dd = new DoublyLinkedList();
        dd.push("asdad");
        dd.push("wwwwwww");
        System.out.println(dd.toString());
    }

    public void push(String val) {
        Node newOne = new Node(val);
        if(length == 0) {
            head = newOne;
            tail = newOne;
        } else {
            tail.next = newOne;
            newOne.prev = tail;
            tail = newOne;
        }

        length++;
    }

    @Override
    public String toString() {
        return "DoublyLinkedList [head=" + head + ", tail=" + tail + ", length=" + length + "]";
    }

}

0 个答案:

没有答案