##LeetCode—138. Copy List with Random Pointer
####题目
https://leetcode.com/problems/copy-list-with-random-pointer/description/
深拷贝一个链表。这个链表的节点有两个指针,其中有一个随机指针,随机指向某个节点。
####思考与分析
第一次接触深拷贝相关的题目。查了一下资料,知道了深拷贝与浅拷贝的区别。
浅拷贝:拷贝一个对象时,仅仅复制对象的引用,,拷贝对象和源对象指向同一个实体。这样,对拷贝对象修改时,原对象也会发生修改。
深拷贝:同时拷贝对象的引用和对象的值,相当于更“完整”的复制了一个对象。拷贝对象和原对象相互之间不再影响。
这道题是一道深拷贝的题。直接网上搜了一下方法。
假设原链表如下图所示,其中细线表示next指针,粗线表示random指针
这里用这样的方法来得到拷贝的链表:按顺序的步骤
1.拷贝每一个节点到他本身的next
2.对于有random指针的节点,拷贝的节点的random指针指向源节点random指针的下一个节点。。有点绕,直接看下图就可以,很简单
3.将拷贝节点挑出来放到新的链表里
####代码
/**
* 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 insertNode = new RandomListNode(fastNode.label);
insertNode.next = fastNode.next;
fastNode.next = insertNode;
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 newList = fastNode.next;
fastNode.next = newList.next;
if(fastNode.next != null){
newList.next = newList.next.next;
}
fastNode = fastNode.next;
}
return newHead;
}
}