LeetCode(138) 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.

public class l138_copy_list_with_random_pointer {
    class RandomListNode {
        int val;
        RandomListNode next, random;

        RandomListNode(int x) {
            this.val = x;
        }
    }

    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if (head == null) return head;
            //第一遍掃描:對每個結點進行復制,把複製出來的新結點插在原結點之後
            RandomListNode node = head;
            while (node != null) {

                //複製
                RandomListNode newnode = new RandomListNode(node.val);
                //插入
                newnode.next = node.next;
                node.next = newnode;
                //進行下一步
                node = newnode.next;
            }
            //第二遍掃描:根據原結點的random,給新結點的random賦值
            node = head;//初始指向頭結點
            while (node != null) {
                if (node.random != null) {
                    node.next.random = node.random.next;//新節點random賦值
                    node = node.next.next;
                }
            }
            //第三遍掃描:把新結點從原鏈表中拆分出來
            RandomListNode newhead = head.next;
            node = head;
            while (node != null) {
                RandomListNode newnode = node.next;//新指針指向copy節點
                node.next = newnode.next;
                if (newnode.next != null) {
                    newnode.next = newnode.next.next;
                }
                node = node.next;
            }
            return newhead;


        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章