138. Copy List with Random Pointer
題目
給定一個鏈表,每個結點包含一個額外的隨機指針,可以指向列表中的任意結點或者指向null。
深拷貝這個鏈表。
代碼塊
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return null;
RandomListNode fastNode = head;
while(fastNode != null){
RandomListNode insert = new RandomListNode(fastNode.label);
insert.next = fastNode.next;
fastNode.next = insert;
fastNode = fastNode.next.next;//無需再添加判別
}
fastNode = head;
while(fastNode != null){
if(fastNode.random != null){
fastNode.next.random = fastNode.random.next;
}
fastNode = fastNode.next.next;
}
fastNode = head;
RandomListNode newHead = head.next;
while(fastNode != null){
RandomListNode newNode = fastNode.next;
fastNode.next = newNode.next;
if(newNode.next != null){//注意是next
newNode.next = newNode.next.next;
}
fastNode = fastNode.next;
}
return newHead;
}
}
代碼分析
這道題第一次看到跳過去了,完全沒有思路。經過張同學的講解,才理清了思路。
第一步:複製鏈表結點;
第二步:複製隨機Random指針;
第三步:進行拆分。
注意二三步的判別條件。