Copy List with Random Pointer 带随机指针的链表的拷贝

来源:互联网 发布:华为sa1456c改mac 编辑:程序博客网 时间:2024/06/04 18:50

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.

这道题其实还蛮绕的

假设链表为1->3->2->5首先进行普通的拷贝

接着:假设1的随之指针指向2.

那么新生成的链表1->3->2->5怎么知道让1指向2呢?

需要几步:

1. 1 知道指向2

2. 即知道值为2 指向index = 2的节点(从0开始) hashmap: index to node

3. 如何知道index = 2的节点呢?假设原来的1指向2 这个节点,要是2这个节点又知道自己的下标 就可了。hashmap: node to index

运行时间:


代码:

public class CopyListwithRandomPointer {    public RandomListNode copyRandomList(RandomListNode head) {        Map<RandomListNode, Integer> nodeToIndexMap = new HashMap<>();        Map<Integer, RandomListNode> indexToNodeMap = new HashMap<>();        RandomListNode fakeHead = new RandomListNode(-1), fakeNode = fakeHead;        RandomListNode cur = head;        int i = 0;        while (cur != null) {            nodeToIndexMap.put(cur, i);            fakeNode.next = new RandomListNode(cur.label);            fakeNode = fakeNode.next;            cur = cur.next;            i++;        }        i = 0;        RandomListNode newcur = fakeHead.next;        while (newcur != null) {            indexToNodeMap.put(i, newcur);            newcur = newcur.next;            i++;        }        newcur = fakeHead.next;        cur = head;        while (newcur != null) {            newcur.random = indexToNodeMap.get(nodeToIndexMap.get(cur.random));            newcur = newcur.next;            cur = cur.next;        }        return fakeHead.next;    }}


1 0
原创粉丝点击