含有随机链表的节点:链表中除了含有指向下一个节点的next,还有一个随机的节点rand。
思路1:我们使用一个哈希表来进行存储数据。
将链表中的节点与新创建的节点进行一一对应。这样我们在复制的时候就可以根据哈希表来进行操作。
思路2:我们不适用额外的空间结构。我们将新创建的链表放在原有链表节点中的后面。然后在复制随机节点的时候,我们只需要找到当前节点的随机节点的后面那个节点就是我们要复制的随机节点。
package lianxi03;
import java.util.HashMap;
public class Code11_CopyListWithRandom {
public static void main(String[] args) {
Node head;
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; // 1 -> 6
head.next.rand = head.next.next.next.next.next; // 2 -> 6
head.next.next.rand = head.next.next.next.next; // 3 -> 5
head.next.next.next.rand = head.next.next; // 4 -> 3
head.next.next.next.next.rand = null; // 5 -> null
head.next.next.next.next.next.rand = head.next.next.next; // 6 -> 4
printRandomList(head);
Node head1=CopyList(head);
printRandomList(head1);
Node head2=CopyList2(head);
printRandomList(head2);
}
public static class Node{
public int value;
public Node next;
public Node rand;
public Node(int data){
this.value=data;
}
}
public static Node CopyList(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 CopyList2(Node head){
if(head==null) return head;
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 printRandomList(Node head){
Node cur=head;
System.out.print("Order ");
while (cur!=null){
System.out.print(cur.value+" ");
cur=cur.next;
}
System.out.println();
System.out.print("rand ");
cur=head;
while (cur!=null){
System.out.print(cur.rand==null?"- ":cur.rand.value+" ");
cur=cur.next;
}
}
}