HELP! My Java solution: "Memory Limit Exceeded"


  • 0
    F

    Hello guys, this is my code and can't seem to make it run

    class Solution {
        public ListNode reverseList(ListNode head) {
           if (head == null) { return null; }
           
           if (head.next == null) { return head; }
           
           Stack<ListNode> nodes = new Stack<ListNode>();
           ListNode present = head;
           
           while ( present != null) {
               nodes.push(present);
               present = present.next;
           }
           
           ListNode newHead = nodes.pop();
           ListNode newPresent = newHead;
           
          while ( !nodes.empty()){
               newPresent.next = nodes.pop();
               newPresent = newPresent.next;
           }
           
           return newHead;
       }
    }
    
    

    I already checked the solution but would like to make this one work first. It seems I am running out of memory but in Eclipse this works just fine (debugging). Can you help me out and spot what can be wrong?

    Thank you


  • 0
    F

    The problem with this solution is that the last node (newPresent) processed by the second while loop doesn't have null at its .next link... so that's why it's looping infinitely when the program is trying to loop through every node of the reversed list (this is not done in the algorithm itself but in the testing code leetcode uses).
    It is easily fixed by doing newPresent.next = null after the last while loop is executed.

    It is important to say this solution is O(2n) in time complex. BUT it takes a bit longer than other approaches to execute, twice the time as if only one loop was used O(n).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.