Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Solution

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
   public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) return null;

        RandomListNode runner = head;
        while (runner != null) {
            RandomListNode next = runner.next;
            RandomListNode copy = new RandomListNode(runner.label);
            runner.next = copy;
            copy.next = next;

            runner = next;
        }

        runner = head;
        while (runner != null) {
            RandomListNode copy = runner.next;
               if (runner.random != null) {
                copy.random = runner.random.next;
            }
            runner = copy.next;
        }

        runner = head;
        RandomListNode result = runner.next;
        while (runner != null) {
            RandomListNode copy = runner.next;
            runner.next = copy.next;

            runner = runner.next;
            if (runner == null) {
                break;
            }
            copy.next = runner.next;
        }

        return result;
    }
}

results matching ""

    No results matching ""