一、复制带随机指针的链表:
难点:复制链表的及链表的下一节点不难实现,但是链表中的随机指针由于不知道指向的节点的地址,所以在用HashMap来实现对应拷贝;
思路:
1、定义一个HashMap,其中key保存原链表的每一个节点,value则保存一个新的节点,使其值等于原链表的节点的值(相当于拷贝了一个节点,但是只拷贝val属性,不拷贝next,random属性);
2、通过while循环来遍历原链表的每一个节点,并同时使用map.get方法取出对应的拷贝节点,并且设置拷贝节点的next值为map.get(head.next):因为两个链表的节点是对应的,所以逻辑关系也是对应的,拷贝后的节点的next节点就是map中拷贝前的节点的next节点的value值。
3、random的设置也是相同的,不过需要判断是否为null的条件。
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
class Solution {
public Node copyRandomList(Node head) {
Map<Node,Node> map = new HashMap<Node,Node>();
Node modify_head = head;
while(head != null){
//将当前节点作为key,创建一个与当前节点值相同的节点,作为value
map.put(head,new Node(head.val));
head = head.next;
}
head = modify_head;
Node new_head = map.get(head);
while(head != null){
new_head.next = map.get(head.next);
if(head.random != null){
new_head.random = map.get(head.random);
}
new_head = new_head.next;
head = head.next;
}
return map.get(modify_head);
}
}