您的位置:首页 > 运维架构

LeetCode Copy List with Random Pointer

2016-02-29 15:15 453 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: