题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
分析:
思路1:
先复制原始链表的结点
在元素链表的头结点开始找每个结点的random。每次都要从头开始找,然后连接起来,所以时间复杂度是o(n*n)
思路2:
用空间换时间。创建一个map映射表。
/**
* 复杂链表的复制
*/
public class CopyList {
public RandomListNode Clone(RandomListNode pHead){
if(pHead == null){
return null;
}
//创建复制后的链表
cloneNodes(pHead);
//连接复制节点的兄弟节点
connectSibling(pHead);
//将原始节点和复制节点分开
return reconnectNodes(pHead);
}
//复制节点
public void cloneNodes(RandomListNode head){
RandomListNode nowNode = head;
while(nowNode != null){
RandomListNode clonedNode = new RandomListNode(nowNode.label);
clonedNode.next = nowNode.next;
nowNode.next = clonedNode;
nowNode = clonedNode.next;
}
}
//连接复制节点的兄弟节点
public void connectSibling(RandomListNode head){
RandomListNode nowNode = head;
while(nowNode != null){
RandomListNode cloned = nowNode.next;
if(nowNode.random != null){
cloned.random = nowNode.random.next;
}
nowNode = cloned.next;
}
}
//将原始节点和复制节点分开
public RandomListNode reconnectNodes(RandomListNode head){
RandomListNode clonedHead = head.next;
RandomListNode nowNode = head;
while(nowNode != null){
RandomListNode clonedNode = nowNode.next;
nowNode.next = clonedNode.next;
clonedNode.next = clonedNode.next == null ? null : clonedNode.next.next;
nowNode = nowNode.next;
}
return clonedHead;
}
public static void main(String[] args) {
RandomListNode head = new RandomListNode(1);
RandomListNode node1 = new RandomListNode(2);
RandomListNode node2 = new RandomListNode(3);
head.next = node1;
node1.next = node2;
head.random = node2;
node1.random = node2;
node2.random = head;
CopyList test = new CopyList();
RandomListNode cloneHead = test.Clone(head);
while(cloneHead != null){
if(cloneHead.random != null){
System.out.println(cloneHead.random.label);
}else{
System.out.println("-");
}
cloneHead = cloneHead.next;
}
}
}
class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}