首页 > 其他 > 详细

LeetCode之Copy List with Random Pointer

时间:2014-03-22 14:10:07      阅读:463      评论: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.

put the nodes in the original linked list to keep track of the order

bubuko.com,布布扣

                                                                                  (图片转自网络,如有侵犯,请告知)

/**
 * 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, *q;
		p = head;
		while (p){
			q = p->next;
			RandomListNode*node=new RandomListNode(p->label);
			node->next = q;
			p->next = node;
			p = q;
		}
		p = head;
		
		while (p){
			q = p->next;
			q->random = (p->random?p->random->next:NULL);
			p = q->next;
		}
		
		p = head;
		RandomListNode *copylist = p->next;
		while (p->next){
			q = p->next;
			p->next = q->next;
			p = q;
		}
		return copylist;
    }
};


LeetCode之Copy List with Random Pointer,布布扣,bubuko.com

LeetCode之Copy List with Random Pointer

原文:http://blog.csdn.net/smileteo/article/details/21790255

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!