ListNode [source code]

 public class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }

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

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

     static ListNode append(ListNode h1, ListNode 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;
        ListNode res = new ListNode(h1.val);
        ListNode cur = res;
        h1 = h1.next;
        while (h1 != null) {
            cur.next = new ListNode(h1.val);
            cur = cur.next;
            h1 = h1.next;
        }
        while (h2 != null) {
            cur.next = new ListNode(h2.val);
            cur = cur.next;
            h2 = h2.next;
        }
        return res;
     }

     static void attach(ListNode h1, ListNode 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 ('[');
        ListNode cur = this;
        while (cur != null) {
            sb.append (cur.val + " ");     // don't use ' ' here!
            cur = cur.next;
        }
        return sb.toString () + ']';
     }

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

results matching ""

    No results matching ""