Search code examples
javalinked-listunreachable-codeunreachable-statement

Java error: unreachable statement when create new linked list node


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.


Solution

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