簡體   English   中英

為什么將第二個元素添加到雙鏈表時會發生堆棧溢出?

[英]Why does stack overflow occur when adding second elements to a double-linked list?

我創建了一個雙鏈表,它可以運行而沒有任何錯誤。但是當我使用調試檢查這個程序時,在添加第二個元素時會出現 java.lang.StackOverflowError。如果我不覆蓋 toString(),程序將正常。但我想知道為什么不覆蓋 toString()? package com.study.testcollection.com.study.testlinkedlist;

public class Node {
    private Node per;
    private Object obj;
    private Node next;
    public Node getPer() {
        return per;
    }
    public Object getObj() {
        return obj;
    }
    public Node getNext() {
        return next;
    }
    public void setPer(Node per) {
        this.per = per;
    }
    public void setObj(Object obj) {
        this.obj = obj;
    }
    public void setNext(Node next) {
        this.next = next;
    }
    @Override
   //if don't write this function,the program will be normal.Why?
    public String toString() {
        return "Node{" +
                "per=" + per +
                ", obj=" + obj +
                ", next=" + next +
                '}';
    }
}
package com.study.testcollection.com.study.testlinkedlist;
public class Mylinkedlist {
    Node first = null;
    Node last = null;
    public void add(Object e){
        if (first == null){
            Node n = new Node();
            n.setObj(e);
            n.setPer(null);
            n.setNext(null);
            first = n;
            last = n;
        }
        else{
            Node n = new Node();
            n.setObj(e);
            last.setNext(n);
            n.setPer(last);
            n.setNext(null);
            last = n;
        }
    }
    public static void main(String[] args) {
        Mylinkedlist a = new Mylinkedlist();
        a.add("hello");
        a.add("Bob");//occur error when it is executed
    }
}

您的“下一個”字段指向一個節點,因此 Node.toString() 被無限調用,導致堆棧溢出。 如果需要使用 toString() 方法,可以修改如下:

public String toString() {
        String n = next != null ? next.obj.toString():"null";
        String p = per != null ? per.obj.toString():"null";
        return "Node{" +
                "per=" + p +
                ", obj=" + obj +
                ", next=" + n +
                '}';
    }

在此處輸入圖像描述

這就是它的外觀。 當你這樣做時:

System.out.println(a.first.toString());

toString定義為:

public String toString() {
    return "Node{" +
            "per=" + per +
            ", obj=" + obj +
            ", next=" + next +
            '}';
}
  • 您嘗試打印下一個n
  • n per嘗試打印前一個
  • 上一個per再次嘗試打印next
  • next調用上一個per等等...

導致堆棧溢出,因為調用永遠不會結束。 如上圖所示,您一次又一次地迭代前進箭頭和前一個箭頭。

要修復它,您可以從Node中刪除toString並替換為:

public String forward() {
    return "Node{" +
            ", obj=" + obj +
            ", next=" + next +
            '}';
}

public String backward() {
    return "Node{" +
            ", obj=" + obj +
            ", prev=" + per +
            '}';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM