Run time error Copy list with Random Node


  • 1
    C

    Causing run time error on the input test case; approach is of copying a node and inserting it after the original node

    **class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
        }
        if(head.next == null){
            RandomListNode copyHead = new RandomListNode(head.label);
            copyHead.next = head.next;
            copyHead.random = head.random;
            return copyHead;
        }
        RandomListNode tail = head;
        while(tail != null){
            RandomListNode copy = new RandomListNode(tail.label);
            copy.next = tail.next;
            tail.next = copy;
            tail = copy.next;
        }
        tail = head;
        while(tail != null){
            RandomListNode itsCopy = tail.next;
            itsCopy.random = tail.random == null ? null : tail.random.next;
            tail = itsCopy.next;
        }
        RandomListNode copyTail = head.next;
        RandomListNode copyHead = copyTail;
        tail = head;
        while(copyTail.next != null){
            tail.next = copyTail.next;
            tail = tail.next;
            copyTail.next = tail.next;
            copyTail = copyTail.next;
            if(copyTail.next == null){
                tail.next = null;
            }
        }
        return copyHead;
    }
    }**

  • 1
    V

    Run time error is caused due to wrong handling of empty input list, when list is empty one need to return null but in the above program this case is not handled , and in the line 6 an attempt is made to access the next field of a null pointer which causes a NullPointerException


Log in to reply
 

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