Java中LinkedList的异常行为

Nit*_*hod 0 java linked-list data-structures

我试图解决需要使用的“黑客等级”问题LinkedList,但发现了一些奇怪的问题。目的是打印LinkedList反面。

我已经尝试调试程序,但是找不到任何错误。

在下面的第一段代码中,我只能将的第一个和最后一个元素LinkedList放入ArrayList

static void reversePrint(SinglyLinkedListNode head) {
    List<Integer> tempList = null;

    if (head == null)
        return;
    else {
        tempList = new ArrayList<>();
        tempList.add(head.data);
        while(head.next != null)
            head = head.next;
        tempList.add(head.data);
    }
    System.out.println("Size of the List -"+tempList.size());
    for(int i = tempList.size()-1; i >= 0; i--)
        System.out.println("Index +"+i+" "+tempList.get(i));
}
Run Code Online (Sandbox Code Playgroud)

在下面的代码中,我将java.lang.OutOfMemoryError: Java heap space无法理解实际上是什么导致了此错误。

static void reversePrint(SinglyLinkedListNode head) {
    List<Integer> tempList = null;

    if (head == null)
        return;
    else {
        tempList = new ArrayList<>();
        while(head.next != null)
            tempList.add(head.data);
        head = head.next;
    }
    tempList.add(head.data);
    System.out.println("Size of the List -"+tempList.size());
    for(int i = tempList.size()-1; i >= 0; i--)
        System.out.println("Index +"+i+" "+tempList.get(i));
}
Run Code Online (Sandbox Code Playgroud)

rda*_*das 5

您应该始终在代码块周围使用方括号。

static void reversePrint(SinglyLinkedListNode head) { 
    List tempList = null;

    if (head == null)
        return;
    else{
        tempList = new ArrayList<Integer>();
        while(head.next != null) {
            tempList.add(head.data);
            head = head.next;
        }
    }
    tempList.add(head.data);
    System.out.println("Size of the List -"+tempList.size());
    for(int i = tempList.size()-1;i>=0;i--)
        System.out.println("Index +"+i+" "+tempList.get(i));   

}
Run Code Online (Sandbox Code Playgroud)

您的代码使得while循环仅是一条语句: tempList.add(head.data);

progress语句head = head.next;不是循环的一部分。因此,您的循环是无限的。这就是为什么您收到OOM错误。我刚刚添加了括号。

编辑:第一种方法也一样。它没有在列表中添加任何内容-只是浏览了链接列表(也添加了括号)