首页 > 解决方案 > Java 中 LinkedList 的意外行为

问题描述

我正在尝试解决需要使用的 Hacker Rank 问题,但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));
}

在下面的代码中,我得到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));
}

标签: javadata-structureslinked-list

解决方案


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

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));   

}

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

进度语句head = head.next;不是循环的一部分。所以你的循环是无限的。这就是您收到 OOM 错误的原因。我只是添加了括号。

编辑:第一种方法也是如此。它没有向列表中添加任何内容 - 只是通过链接列表(也在那里添加括号)


推荐阅读