美文网首页
复制含有随机指针节点的链表

复制含有随机指针节点的链表

作者: shoulda | 来源:发表于2018-07-16 15:39 被阅读0次

题目:一种特殊的链表节点类描述如下:

思路:利用HashMap来进行操作

//节点的定义
public static class Node {
        public int value;
        public Node next;
        public Node rand;

        public Node(int data) {
            this.value = data;
        }
    }

public static Node copyListWithRand1(Node head) {
        HashMap<Node, Node> map = new HashMap<Node, Node>();
        Node cur = head;
        while (cur != null) {
            map.put(cur, new Node(cur.value));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).rand = map.get(cur.rand);
            cur = cur.next;
        }
        return map.get(head);
    }

相关文章

网友评论

      本文标题:复制含有随机指针节点的链表

      本文链接:https://www.haomeiwen.com/subject/gdjbpftx.html