给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
您在真实的面试中是否遇到过这个题?
Yes
样例
挑战
可否使用O(1)的空间
标签 Expand
相关题目 Expand
看似普通的链表操作,只是多了一个随机指针。
但是在遍历深度拷贝时候,会出现随机指针并不存在的情况,这就无法去指向随机指针。
但是可以用下面这种方式
--------------------------------------|
1.原始链表:1-------> 2 ------->3---------->4----------->5
-----------------------^
红色表示random指针。
2.在原始链表后复制原始链表的节点:
--------------------------------------------------------------------------------------------|
1
-------> 1
------->2
---------->2
----------->3
---------> 3
-------> 4
------->4
---------->5
----------->5
--------------------------------------------------^
3. 复制原始链表的random指针
cur.next.random = cur.random.next;
------------------------------------------------------------------------------|
-------------------------------------------------------------------------------|
1
-------> 1
------->2
---------->2
----------->3
---------> 3
-------> 4
------->4
---------->5
----------->5
--------------------------------------------------^
----------------------------------------------------^
4.将新旧链表的节点分离。
/**
* 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 {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
// write your code here
if(null==head) return null;
/*复制原始链表*/
RandomListNode cur = head;
while(null!=cur){
RandomListNode newcur = new RandomListNode(cur.label);
newcur.next = cur.next;
cur.next = newcur;
cur = cur.next.next;
}
/**复制链表的random指针**/
cur = head;
while(null!=cur){
if(null!=cur.random){
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
/**拆分新旧链表**/
cur = head;
RandomListNode newhead = head.next;
while(null!=cur){
RandomListNode newcur = cur.next;
if(null!=newcur){
cur.next = newcur.next;
}
if (newcur.next != null) newcur.next = newcur.next.next;
cur = cur.next;
}
return newhead;
}
}