HELP! My Java solution: "Memory Limit Exceeded"

  • 0

    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 ( == null) { return head; }
           Stack<ListNode> nodes = new Stack<ListNode>();
           ListNode present = head;
           while ( present != null) {
               present =;
           ListNode newHead = nodes.pop();
           ListNode newPresent = newHead;
          while ( !nodes.empty()){
      = nodes.pop();
               newPresent =;
           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

    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 = 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.