【Leetcode】138. Copy List with Random Pointer

Question:

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.

Tips:

本题的链表结构不同于以往的链表,结构如下:

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

将该链表复制出来,并返回(包括结点的label next random)。

思路:

①复制结点值以及next指针。就一个结点而言,新建一个结点,使其的label值等于被复制结点的label,并将新节点接在原结点之后。

②复制random指针。我将每一个新建的结点都接在了原结点之后,那么新节点的random指针就是old结点的random的next,即

result.next.random = result.random.next;

③将新旧结点分开即可。

代码:

public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null)
            return null;

        RandomListNode head1 = head;

        // 新建结点 并接在原来节点的后面
        while (head1 != null) {
            RandomListNode h = new RandomListNode(head1.label);
            if (head1.next != null) {
                RandomListNode next = head1.next;
                head1.next = h;
                h.next = next;
            } else {
                head1.next = h;
                h.next = null;
            }
            head1 = head1.next.next;
        }
        RandomListNode result = head;
        // 赋值random指针。
        while (result != null) {
            System.out.println("ceshi  result" + result.label);
            if (result.random != null && result.next != null) {
                result.next.random = result.random.next;
            }
            result = result.next.next;
        }
        // 将两个链表分开 还原
        RandomListNode old = head;
        RandomListNode pnew = head.next;
        RandomListNode new1 = pnew;
        while (pnew.next != null) {
            System.out.println("test new de label" + pnew.label);
            old.next = pnew.next;
            old = old.next;
            pnew.next = old.next;
            pnew = pnew.next;
        }
        old.next = null;
        pnew.next = null;
        return new1;
    }

测试代码:

public static void main(String[] args) {
        RandomListNode r1 = new RandomListNode(1);
        RandomListNode r2 = new RandomListNode(2);
        RandomListNode r3 = new RandomListNode(3);
        r1.next = r2;
        r2.next = r3;
        r3.next = null;

        r1.random = r3;
        L138CopyListWithRandompPointer l138 = new L138CopyListWithRandompPointer();
        RandomListNode r = l138.copyRandomList(r1);
        while (r != null) {
            System.out.println(r.label + "^^^^");
            if (r.random != null)
                System.out.println(r.random.label + "~~~~random");
            else
                System.out.println("random null");
            r = r.next;
        }
    }

 

posted @ 2018-02-26 09:39  于淼  阅读(117)  评论(0编辑  收藏  举报