【LeetCode】#138复制带随机指针的链表(Copy List with Random Pointer)
题目描述
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深度拷贝。
Description
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.
解法
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null){
return null;
}
RandomListNode curNode = head;
RandomListNode cpNode;
while(curNode!=null){
cpNode = new RandomListNode(curNode.label);
cpNode.next = curNode.next;
curNode.next = cpNode;
curNode = cpNode.next;
}
curNode = head;
while(curNode!=null){
if(curNode.random!=null){
curNode.next.random = curNode.random.next;
}
curNode = curNode.next.next;
}
curNode = head;
RandomListNode retNode = head.next;
while(curNode!=null){
cpNode = curNode.next;
curNode.next = cpNode.next;
if(cpNode.next!=null){
cpNode.next = cpNode.next.next;
}else{
cpNode.next = null;
}
curNode = curNode.next;
}
return retNode;
}
}