【Leetcode】138. Copy List with Random Pointer

於淼發表於2018-02-26

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;
        }
    }

 

相關文章