给定一个由Node节点类型组成的无环单链表的头节点head,请实现一个函数完成这个链表中所有结构的复制,并返回复制的新链表的头节点。 进阶:不使用额外的数据结构,只用有限几个变量,且在时间复杂度为 O(N) 内完成原问题要实现的函数。
import java.util.HashMap;
public class e14CopyListWithRandom {
public static class Node {
public int value;
public Node next;
public Node rand;
public Node(int data) {
this.value = data;
}
}
public static Node copyListWithRand1(Node head){
HashMap<Node,Node> map=new HashMap<>();
Node cur= head;
while(cur!=null){
map.put(cur,new Node(cur.value));
cur=cur.next;
}
cur=head;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).rand=map.get(cur.rand);
cur=cur.next;
}
return map.get(head);
}
public static Node copyListWithRand2(Node head){
if(head==null){
return null;
}
Node cur=head;
Node next=null;
while(cur!=null){
next=cur.next;
cur.next=new Node(cur.value);
cur.next.next=next;
cur=next;
}
cur=head;
Node curCopy=null;
while (cur!=null){
next=cur.next.next;
curCopy=cur.next;
curCopy.rand=cur.rand!=null?cur.rand.next:null;
cur=next;
}
Node res=head.next;
cur=head;
while(cur!=null){
next=cur.next.next;
curCopy=cur.next;
cur.next=next;
curCopy.next=next!=null?next.next:null;
cur=next;
}
return res;
}
public static void printRandLinkedList(Node head){
Node cur=head;
System.out.print("Order: ");
while(cur!=null){
System.out.print(cur.value+" ");
cur=cur.next;
}
System.out.println();
cur=head;
System.out.print("Rank: ");
while (cur!=null){
System.out.print(cur.rand==null?"- ":cur.rand.value+" ");
cur=cur.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = null;
Node res1 = null;
Node res2 = null;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.rand = head.next.next.next.next.next;
head.next.rand = head.next.next.next.next.next;
head.next.next.rand = head.next.next.next.next;
head.next.next.next.rand = head.next.next;
head.next.next.next.next.rand = null;
head.next.next.next.next.next.rand = head.next.next.next;
printRandLinkedList(head);
res1 = copyListWithRand1(head);
printRandLinkedList(res1);
res2 = copyListWithRand2(head);
printRandLinkedList(res2);
System.out.println("=========================");
}
}