题目: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.
刚读完题目之道是要返回一个带随机指针的链表的复制。其实还是不太明白题目意思。所以直接看了别人的解答,读完之后大概明白了是什么意思。就是返回一个与原来列表一模一样的链表即可。结题思路如下:
在原链表每个节点后面插入一个复制节点,即先把原链表中的节点都复制一边;
调整这些复制节点的Random域的值了,使其指向与原链表对应节点的复制节点;
调整所有复制节点的Next域的值,并恢复原始链表所有节点的Next的值到初始状态!
这样就很清晰了,代码分三次循环分别完成上述三个目标即可,这种方法击败了70%多的用户。代码入下:
public static RandomListNode copyRandomList1(RandomListNode head) {
RandomListNode iter = head, next;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != null) {
next = iter.next;
RandomListNode copy = new RandomListNode(iter.label);
iter.next = copy;
copy.next = next;
iter = next;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
RandomListNode pseudoHead = new RandomListNode(0);
RandomListNode copy, copyIter = pseudoHead;
while (iter != null) {
next = iter.next.next;
// extract the copy
copy = iter.next;
copyIter.next = copy;
copyIter = copy;
// restore the original list
iter.next = next;
iter = next;
}
return pseudoHead.next;
}