LeetCode: Copy List with Random Pointer [138]

【题目】

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.


【题意】

    给定一个链表,每个节点除了next指针外,还有一个random指针,指向任意的节点。
    要求,复制这样的一个链表


【思路】

    思路1:
    先一次生成每个节点对应的新节点,并用hashmap记录新旧节点之间的对应关系,然后再更新random指针
    
    思路2:
    一次生成每个旧节点的新节点,然后把新节点插入到旧节点的后继。
    这样random直接的对应关系也就有了
    new->random=old->random->next;

    


【代码】

/**
 * 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) {
        map<RandomListNode*, RandomListNode*> old2new;
		
		RandomListNode*newhead=NULL;
		RandomListNode*oldpointer=head;
		RandomListNode*newpointer=NULL;
		RandomListNode*prevnew=NULL;
		//生成新链表构造旧链表结点和新链表结点的对应关系
		while(oldpointer){
			newpointer=new RandomListNode(oldpointer->label);
			if(prevnew==NULL)newhead=newpointer;
			else{
				prevnew->next=newpointer;
			}
			prevnew=newpointer;
			
			old2new[oldpointer]=newpointer;
			oldpointer=oldpointer->next;
		}
		//更新random指针
		oldpointer=head;
		newpointer=newhead;
		while(oldpointer){
			newpointer->random=old2new[oldpointer->random];
			oldpointer=oldpointer->next;
			newpointer=newpointer->next;
		}
		return newhead;
    }
};


猜你喜欢

转载自blog.csdn.net/HarryHuang1990/article/details/35596033