【LeetCode】【138】【Copy List with Random Pointer】【链表】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012503241/article/details/82868105

题目: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;
    }

猜你喜欢

转载自blog.csdn.net/u012503241/article/details/82868105