A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
题意:给出一个链表,包含next和random结点,作深拷贝
思路:链表的遍历操作
代码如下:
class RandomListNode
{
int label;
RandomListNode next, random;
RandomListNode(int x) {this.label = x;}
}
class Solution
{
public RandomListNode copyRandomList(RandomListNode head)
{
if (null == head) return null;
RandomListNode new_head = new RandomListNode(head.label);
RandomListNode current = head, new_current = new_head;
while (current != null)
{
if (current.next != null)
{
new_current.next = new RandomListNode(current.next.label);
}
if (current.random != null)
{
new_current.random = new RandomListNode(current.random.label);
}
current = current.next;
new_current = new_current.next;
}
return new_head;
}
}