LeetCode: Copy List with Random Pointer [138]

本文探讨了如何解决链表复制问题,特别是当链表中的每个节点包含一个额外的random指针时。通过两种策略实现了链表的深拷贝:第一种策略先生成所有节点的副本并建立映射关系,随后更新random指针;第二种策略在生成副本的同时,将新节点插入到原节点之后,从而自动维护random指针的对应关系。

【题目】

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值