Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

Getting runtime error

0 votes
160 views

Hi. I'm getting a runtime error for this with Last executed input: {5}, 1, 1

The code is not great, but i've tested it on my machine and it appears to work. Moreover, because of the very first if condition, I have no idea how that test case could fail :S

public ListNode reverseBetween(ListNode head, int m, int n) {
    if(head == null || m == n) return head;
    ListNode head_ = head; // save old head

    for(int i = 1; i < m-1; i++) head = head.next;

    ListNode start = head;
    ListNode revEnd = m == 1 ? head : head.next;
    ListNode prev = revEnd;
    head = prev;

    for(int i = m; i <= n; i++){
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }

    // Thread appropriately
    revEnd.next = head;

    if(m == 1) head_ = prev; // if we need to replace the head
    else       start.next = prev;

    return head_;
}

Anyone see any problems? I'm surprised since it shouldn't get any farther than the first if statement. Thanks.

asked Dec 13, 2013 in Reverse Linked List II by rafalio (260 points)

That's curious, indeed. I tried your code and it crashed with a runtime error; then I tried mine and it went through without problem. I wonder if your problem is not with another test case. In particular, are you sure you don't get a NullPointerException for the instruction head.next = prev when i==n==length of the list?

Yeah, it's probably crashing on some other test case. But I still can't figure it out, tested it on all 1 <= m <= n <= length of list for a list of size 1, 2, 3, 4, 5 and I don't get any errors.

Sorry, I have fixed this issue. Your code is AC now :)

It was an OJ problem? What was it exactly, I'm curious now :)

I'm also very curious!

Please log in or register to answer this question.


...