題目來源:LeetCode(力扣)
給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。
要求返回這個鏈表的深拷貝。
思路:
分三步走,首先,將新老鏈表相互間隔的串爲一個鏈表;然後,處理random指針域;最後,將老新鏈表拆開,並返回對應的鏈表頭結點。
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
//1、將新老結點串爲一個鏈表
Node cur = head;
while(cur != null){
Node node = new Node(cur.val,cur.next,null);
Node tmp = cur.next;
cur.next = node;
cur = tmp;
}
//2、處理random指針域
cur = head;
while(cur != null){
if(cur.random != null){
cur.next.random = cur.random.next;
cur = cur.next.next;
}else{
cur.next.random = null;
cur = cur.next.next;
}
}
//3、將老新鏈表拆開,返回新鏈表
cur = head;
Node newHead = cur.next;
while(cur.next != null){
Node tmp = cur.next;
cur.next = tmp.next;
cur = tmp;
}
return newHead;
}
}