
方法一:使用hashmap,其中每个key中存老链表的结点,value中存新链表的结点,然后遍历老链表,通过hashmap来寻找新链表中每个结点的随机指针指向,代码如下:
/*
// Definition for a Node.
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) {
HashMap<Node,Node> map = new HashMap<Node,Node>();
Node cur = head;
while(cur != null){
map.put(cur,new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur != null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
方法二:在老链表中每个结点后插入新结点,在遍历整个链表,此时每个新结点的随机指针指向的就是老结点的随机指针的下一个结点,最后再将新老链表分离,代码如下:
/*
// Definition for a Node.
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) {
Node cur = head;
if(head == null){
return null;
}
while(cur != null){
Node cur1 = new Node(cur.val);
cur1.next = cur.next;
cur.next = cur1;
cur = cur.next.next;
}
cur = head;
while(cur != null){
cur.next.random = cur.random != null ? cur.random.next : null;
cur = cur.next.next;
}
Node res = head.next;
cur = head;
Node copy;
Node next;
while(cur != null){
next = cur.next.next;
copy = cur.next;
cur.next = next;
copy.next = next != null ? next.next : null;
cur = next;
}
return res;
}
}
308




被折叠的 条评论
为什么被折叠?



