leetcode[138]Copy List with Random Pointer

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.

/**

 * 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) {

        RandomListNode *p=head;

        RandomListNode *pnext=NULL;

        RandomListNode *tmp=NULL;

        while(p)

        {

            pnext=p->next;

            tmp=new RandomListNode(p->label);

            p->next=tmp;

            tmp->next=pnext;

            p=pnext;

        }

        p=head;

        while(p)

        {

            if(p->random)p->next->random=p->random->next;

            p=p->next->next;

        }

        RandomListNode *newhead=new RandomListNode(0);

        pnext=newhead;

        p=head;

        while(p)

        {

            pnext->next=p->next;

            pnext=pnext->next;

//            if(pnext->next)p->next=pnext->next;

//            else p->next=NULL;

            p->next=pnext->next;//

            p=p->next;

        }

        return newhead->next;

    }

};

 

你可能感兴趣的:(LeetCode)