RandomListNode [source code]

public class RandomListNode {
    int label;
    RandomListNode next, random;
    RandomListNode(int x) { this.label = x; }

     static RandomListNode buildListNode(int[] values) {
        if (values.length == 0) return null;
        int n = values.length;
        RandomListNode[] nodes = new RandomListNode[n];
        for (int i = 0; i < n; i++) {
            nodes[i] = new RandomListNode(values[i]);
        }
        for (int i = 0; i < n - 1; i++) {
            nodes[i].next = nodes[i + 1];
        }
        return nodes[0];
     }

     static String serialize (RandomListNode node) {
        return node == null ? "[]" : node.toString ();
     }

     static RandomListNode append(RandomListNode h1, RandomListNode h2) {
        // do not just append h2 to the end of h1: that would mutate h1, producing very hard-to-find bug
        if (h1 == null) return h2;
        if (h2 == null) return h1;
        RandomListNode res = new RandomListNode(h1.label);
        RandomListNode cur = res;
        h1 = h1.next;
        while (h1 != null) {
            cur.next = new RandomListNode(h1.label);
            cur = cur.next;
            h1 = h1.next;
        }
        while (h2 != null) {
            cur.next = new RandomListNode(h2.label);
            cur = cur.next;
            h2 = h2.next;
        }
        return res;
     }

     static void attach(RandomListNode h1, RandomListNode h2) {
        if (h1 == null || h2 == null) return;
        while (h1.next != null) {
            h1 = h1.next;
        }
        h1.next = h2;
     }

     public String toString () {
        StringBuilder sb = new StringBuilder ();
        sb.append ('[');
        RandomListNode cur = this;
        while (cur != null) {
            sb.append (String.format ("%d:%s ", cur.label, cur.random != null ? cur.random.label : "null"));     // don't use ' ' here!
            cur = cur.next;
        }
        return sb.toString () + ']';
     }

     static RandomListNode[] buildListNodeArray (int[][] ar) {
        RandomListNode[] res = new RandomListNode[ar.length];
        for (int i = 0; i < ar.length; i++) {
            res[i] = buildListNode (ar[i]);
        }
        return res;
     }
}

Problem Description

results matching ""

    No results matching ""