-1

I wrote a program for merge two linkedlist so I create a dummyHead first. But the compiler returns me an error: unreachable statement. I searched it on Internet but still don't understand why is it.

The code is :

/**
 * class ListNode {
 *   public int value;
 *   public ListNode next;
 *   public ListNode(int value) {
 *     this.value = value;
 *     next = null;
 *   }
 * }
 */
public class Solution {
  public ListNode merge(ListNode one, ListNode two) {
    if(one == null && two != null){
      return two;
    }else if(one != null && two == null){
      return one;
    }else{
      return null;
    }
    
    ListNode dummyHead = new ListNode(-1);
    ListNode cur_one = one;
    ListNode cur_two = two;
    ListNode dummyCur = dummyHead;
    while(cur_one.next == null || cur_two.next == null){
      if(cur_one.value <= cur_two.value){
        dummyCur.next = cur_one;
        cur_one = cur_one.next;
      }else{
        dummyCur.next = cur_two;
        cur_two = cur_two.next;
      }
      dummyCur = dummyCur.next;
    }
    
    if(cur_one.next != null){
      dummyCur.next = cur_one.next;
    }
    if(cur_two.next != null){
      dummyCur.next = cur_two.next;
    }
    
    return dummyHead.next;
  }
}

The error information is :

error:java.io.IOException: /Solution.java:21: error: unreachable statement

ListNode dummyHead = new ListNode(-1);

Thank you for your reply.

Community
  • 1
  • 1
Meilan
  • 434
  • 6
  • 17
  • It means that your program will be terminated before that statement in any case – Ruslan Mar 02 '19 at 22:46
  • Just as the error states, that line of code (and subsequently everything after it) is unreachable. And, as a result, is unnecessary. Under what logical condition do you expect that line of code to ever be reached? – David Mar 02 '19 at 22:47

3 Answers3

2

That line is never executed because of your if/else if/else conditional:

if(one == null && two != null){
  return two;
} else if(one != null && two == null){
  return one;
} else{
  return null;
}

Based on this conditional, two, one, or null is returned before line 21 can be executed.

You'll want to remove the else to allow the method to continue executing.

user4487338
  • 78
  • 1
  • 6
2

else { return null; } The last else condition returns null before that line. Remove last else condition if you expect rest of function to be used.

Edwin M. Cruz
  • 362
  • 1
  • 8
1

In your first if-statement you leave the method with an early exit under all possible circumstances due to the last else-block. That’s why none of the following statements will ever be executed.

dpr
  • 10,591
  • 3
  • 41
  • 71