您的位置:首页 > 其它

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head

2017-02-25 11:14 746 查看
解题思路:

/*

struct RandomListNode {

    int label;

    struct RandomListNode *next, *random;

    RandomListNode(int x) :

            label(x), next(NULL), random(NULL) {

    }

};

*/

class Solution {

public:

   

    RandomListNode* Clone(RandomListNode* pHead)

    {

        if(!pHead) return NULL;

        

        RandomListNode* tmp;

        RandomListNode* t = pHead;

        RandomListNode* head;

        while(t){

           tmp = new RandomListNode(t->label);

           tmp->next = t->next;

           t->next = tmp;

           t = tmp->next;

        }

        

        t = pHead;

        while(t){

            tmp = t->next;

            if(t->random) tmp->random = t->random->next;

            t = tmp->next;    

        }

        t = pHead;

        head = t->next;

        

        while(t->next){

            tmp = t->next;

            t->next = tmp->next;

            t = tmp;

            

        }

        return head;

        

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐