leetCode(7):Copy list with random pointer 分类: leetCode 2015-06-18 08:11 132人阅读 评论(0) 收藏

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) {
        if(head==NULL)
    		return NULL;
    	RandomListNode* p=head;
    	while(p)//复制每个节点
    	{
    		RandomListNode* tmp=p->next;
    		RandomListNode* newNode=new RandomListNode(p->label);
    		p->next=newNode;
    		newNode->next=tmp;
    		p=tmp;
    	}
    	p=head;
    	while(p)//给复制的节点random赋值
    	{
    		if(p->random==NULL)
    			p->next->random=NULL;
    		else
    			p->next->random=p->random->next;
    		p=p->next->next;
    	}
    	
    	p=head;
    	RandomListNode* newHead=p->next;
    	RandomListNode* p1=newHead;
    	while(p)
    	{
    		p->next=p1->next;
    		if((p->next)!=NULL)
    			p1->next=p->next->next;
    		p=p->next;
    		p1=p1->next;
    	}
    	return newHead;
    }
};


原文地址:https://www.cnblogs.com/zclzqbx/p/4687110.html