拷贝带有random域的特殊链表
Copy List with Random Pointer https://leetcode.com/problems/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.
复制的关键点在于:
假设原链表为: A->B->C->D->null
正常拷贝为: A’->B’->C’->D’->null
但是若带有随机域指针,那么在拷贝完原结构后还需要拷贝随机域的结构,可是难点在于,如何将原链表随机域指针指向的那个节点与后来拷贝的对应节点对应上去。因此,关键点在于要将原链表中的节点与复制链表中的节点对应上去。
两种对应方法:
1. 哈希表对应(定义哈希,将A与A’…对应节点对应上)
2. 将对应节点作为原节点的next(即定义链表A->A’->B->B’->C->C’->D->D’->null,这样就对应上了)
此代码展示第二种方式:
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) { this.label = x; }
};
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode iter = head;
for(; iter != null;){
RandomListNode node = new RandomListNode(iter.val);
node.next = iter.next;
iter.next = node;
iter = node.next;
}
for(iter = head; iter != null;){
iter.next.random = iter.random.next;
iter = iter.next.next;
}
RandomListNode newhead = new RandomListNode(0), it = newhead;
for(iter = head; iter != null;){
it.next = iter.next;
iter.next = iter.next.next;
it = it.next;
iter = iter.next;
}
return newhead.next;
}

466

被折叠的 条评论
为什么被折叠?



