leetcode: Copy List with Random Pointer

来源:互联网 发布:比蓝墨云班好用的软件 编辑:程序博客网 时间:2024/05/24 23:14

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.
/*
* 复杂链表表示:存在2个指针,一个指针之后下一个节点,另外一个随机指针指向随机节点
* 分成3步:
* 1. 复制节点,如A-B-C 变成 A-A’-B-B’-C-C’
* 2. 依次遍历节点A,B,C,将这些节点的随机指针与A’B’C’一致
* 3. 分离A-B-C和A’B’C’,A’B’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:    RandomListNode *copyRandomList(RandomListNode *head) {        if (!head)            return nullptr;        RandomListNode *p = head, *q = head->next, *newNode = NULL;        //step 1        while (p != NULL) {            newNode = new RandomListNode(0);            newNode->next = p->next;            p->next = newNode;            newNode->label = p->label;            newNode->random = NULL;            p = q;            if (q)            q = q->next;        }        //step 2        p = head;        q = p->next;        while (q != NULL) {            if (p->random != NULL)                q->random = p->random->next;            if (q->next == NULL)                break;            p = q->next;            if (p)            q = p->next;        }  //step 3        newNode = head->next;        p = head; q = p->next;        while (q != NULL) {            p->next = q->next;            if (q->next == NULL)                break;            q->next = p->next->next;            p = p->next;            q = q->next;        }        return newNode;    }};
0 0
原创粉丝点击