1. 程式人生 > >【LeetCode】【138】【Copy List with Random Pointer】【連結串列】

【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. 解題思路:複雜連結串列的複製問題,每一個節點都有兩個指標,一個指向下一個節點,一個指向隨機的節點。思路是先按照指向下一節點的順序複製出一個簡單鏈表,再用hash表的方法快速找到每個節點指向的隨機節點。 程式碼:

class RandomListNode {
      int label;
      RandomListNode next, random;
      RandomListNode(int x) { this.label = x; }
  };
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null) return null;
        HashMap<RandomListNode,RandomListNode> map = new HashMap<>();  //這個hash表用來快速找到指向的隨機節點
        RandomListNode ans = new RandomListNode(head.label);
        map.put(head,ans);
        //複製單鏈表
        RandomListNode node = ans;
        RandomListNode curr = head;
        curr = curr.next;
        while (curr != null){
            RandomListNode temp = new RandomListNode(curr.label);
            node.next = temp;
            node = node.next;
            map.put(curr,temp);
            curr = curr.next;
        }
        //複製隨機節點
        node = ans;
        while (head!=null){
            if(head.random == null)node.random = null;
            else node.random = map.get(head.random);
            head = head.next;
            node = node.next;
        }
        return ans;
    }