码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode(7):Copy list with random pointer

时间:2015-06-18 09:37:15      阅读:124      评论:0      收藏: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;
    }
};


leetCode(7):Copy list with random pointer

标签:

原文地址:http://blog.csdn.net/walker19900515/article/details/46543765

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!