关键点:
- 方法1:利用hashmap
- 方法2:利用指针
代码
public static Node copyList1(Node head) {
if(head == null) return null;
//1、准备一个HashMap <key,value> <节点,该节点的副本>
HashMap<Node,Node> map = new HashMap<Node, Node>();
Node cur = head;
while(cur != null) {
map.put(cur, new Node(cur.value));
cur = cur.next;
}
//2、复制next指针和rand随机指针
cur = head;
while(cur != null) {
map.get(cur).next = cur.next;
map.get(cur).rand = cur.rand;
cur = cur.next;
}
return map.get(head);
}
public static Node copyList2(Node head) {
if(head == null) return null;
//1、复制节点 1-->2-->3--> ==> 1-->1'-->2-->2'-->3-->3'-->
Node cur = head;
Node next = null;
while(cur != null) {
Node cpCur = new Node(cur.value);
next = cur.next;
cur.next = cpCur;
cpCur.next = next;
cur = next;
}
//2、复制随机指针
cur = head;
Node cpCur = null;
while(cur != null) {
cpCur = cur.next;
cpCur.rand= cur.rand == null ? null : cur.rand.next;
cur = cur.next.next;
}
//3、拆解链表 1-->1'-->2-->2'-->3-->3'--> ==> 1-->2-->3--> + 1'-->2'-->3'-->
cur = head;
Node cpHead = cur.next;
while(cur != null) {
cpCur = cur.next;
next = cur.next.next;
cur.next = next;
cpCur.next = next == null ? null : next.next;
cur = next;
}
return cpHead;
}