Cannot see why this code fails the tests...


  • 0
    N

    Basically I try to complete the goal by:

    1. Adding each copied node right after the original node
    2. Since I know the copied nodes is right after the original nodes, by getting the random nodes of the original, I know the where the random nodes for the copies
    3. Dislink the whole linked list to be the original and copied links

    Thank you for all helps.

    public RandomListNode copyRandomList(RandomListNode head) {
            if(head == null)    return null;
            
            RandomListNode node = head;
            while(node != null) {
                RandomListNode addon = new RandomListNode(node.label);
                addon.next = node.next;
                node.next = addon;
                node = node.next.next;
            }
            
            node = head;
            while(node.next.next != null) {
                node.next.random = (node.random == null) ? null : node.random.next;
                node = node.next.next;
            }
            
            RandomListNode ans = head.next;
            node = head;
            while(node.next.next != null) {
                RandomListNode tmp = node.next;
                node.next = tmp.next;
                tmp.next = tmp.next.next;
                node = node.next;
            }
            
            node.next = null;
            return ans;
        }
    

  • 0

    @nan21 You must have not checked this post.


Log in to reply
 

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