简体   繁体   中英

Unexpected Behaviour of LinkedList in Java

I am attempting to solve a problem on Hacker Rank that requires the use of LinkedList , and I found something strange. The goal is to print the LinkedList in reverse.

I have tried debugging the program, but I'm unable to find anything wrong.

In the first piece of code below, I'm only able to put the first and last elements of the LinkedList into an 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));
}

In the following piece of code, I am getting java.lang.OutOfMemoryError: Java heap space and I am unable to understand what is actually causing this error.

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

You should always use brackets around your code blocks.

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

}

Your code was such that the while-loop was only a single statement: tempList.add(head.data);

The progression statement head = head.next; was not part of the loop. So your loop was infinite. That's why you're getting the OOM error. I just added brackets.

EDIT: Same goes for the first method. It's not adding anything to the list - just going through the linked list (Add brackets there too)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM