您的位置:首页 > 其它

LintCode(105) 复制带随机指针的链表

2016-06-07 21:44 411 查看

题目


复制带随机指针的链表

给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。

分析

一个经典题目,思想就是在复制每个原节点链接其后,然后依次添加新节点的random指针。
遍历复制后的链表,删除原节点。

就不详述了,看代码,重点是练习Python实现~~~

Python代码

# Definition for singly-linked list with a random pointer.
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return None

p = head
while p is not None:
r = p.next
node = RandomListNode(p.label)
node.next = p.next
p.next = node
p = r

p = head
q = p.next

if q is None:
print("None")
while p is not None and q is not None:
if p.random is not None:
q.random = p.random.next
p = q.next
if p is not None:
q = p.next

ret = head.next
del head
q = ret
while q.next is not None:
p = q.next
q.next = p.next
del p
q = q.next

return ret


GitHub -- Python完整代码

C++代码

/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
*     int label;
*     RandomListNode *next, *random;
*     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
if(head == NULL)
{
return NULL;
}//if

RandomListNode *p = head;
while(p != NULL)
{
RandomListNode *r = p->next;
RandomListNode *tmp = new RandomListNode(p->label);
tmp->next = p->next;
p->next = tmp;

p = r;
}//while

p = head;
RandomListNode *q = head->next;
while(p && q)
{
if(p->random)
{
q->random = p->random->next;
}
p = q->next;
if(p)
{
q = p->next;
}

}//while

RandomListNode *ret = head->next;
delete head;
q = ret;
while(q->next)
{
p = q->next;
q->next = p->next;

delete p;

q = q->next;
}//while

return ret;
}
};


GitHub -- C++代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: