Why am I getting a memory exceeded error?


  • 0
    E

    Can someone please explain why this is resulting in a memory limit exceeded error?

    public class Solution {
        public ListNode partition(ListNode head, int x) {
            ListNode begin = new ListNode(x);
            ListNode end = new ListNode(x);
            ListNode currBegin = begin;
            ListNode currEnd = end;
            while(head!=null){
                if(head.val<x){
                    currBegin.next = head;
                    currBegin = currBegin.next;
                    head = head.next;
                }
                else{
                    currEnd.next = head;
                    currEnd = currEnd.next;
                    head = head.next;
                }
            }
            //Combine the end of the beginning list with the beginning of the end list.
            currBegin.next = end.next;
            return begin.next;
        }
    }
    

  • 0
    E

    Huh? I had to include (currEnd.next = null) at the else statement. I think I get it but i still don't fully understand. Does that stop loops?


  • 0
    E

    @elmubark said in Why am I getting a memory exceeded error?:

    Huh? I had to include (currEnd.next = null) at the else statement. I think I get it but i still don't fully understand. Does that stop loops?

    Yes that was the reason. If it end the list with a node that should be on the end list anyway i pass the test without the null needed. Makes sense thanks!


  • 0
    S

    I encountered the same problem
    but I still did not figure it out.
    and did not understand


  • 0
    P
    This post is deleted!

  • 0
    P

    @Superman_NZ
    if input is 2->1 x = 2
    you will get 1->2 (->1 again), that is because you haven't updated the 2.next (tail of the result)


  • 0
    S

    @pppp big thanks , i already figured it out


Log in to reply
 

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