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

Leetcode: Copy List with Random Pointer - 再解

2014-05-26 13:55 288 查看
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.

一种逻辑更清楚的方法:1)复制每个节点并插入到当前节点之后;2)根据当前节点和复制节点直接相邻这个关系设置random指针,copied->random = cur->random->next;3)拆分这个链表为2个记得复制后的链表。

 

/**
* 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:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) {
return head;
}

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

cur = head;
while (cur != NULL) {
if (cur->random != NULL) {
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}

RandomListNode *copied = new RandomListNode(0);
tmp = copied;
cur = head;
while (cur != NULL) {
copied->next = cur->next;
copied = copied->next;
cur->next = copied->next;
cur = cur->next;
}

copied = tmp->next;
delete tmp;

return copied;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 指针 random