剑指offer 35.复杂链表的复制(C++实现)

剑指offer 35.复杂链表的复制(C++实现)

//Definition for a Node
class Node{
public:
	int val;
	Node* next;
	Node* random;
	Node(int _val){
		val = _val;
		next = NULL;
		random = NULL;
	}
};

利用哈希map实现代码:

class Solution{
public:
	Node* copyRandomList(Node* head){
		if(head == nullptr) return nullptr;
		Node* cur = head;
		unordered_map<Node*, Node*>map; //无序map容器,底层实现是哈希表,所以不能进行排序
		//复制节点,建立origin node -> new node 的映射
		while(cur!=nullptr){
			map[cur] = new Node(cur->val);  //
			cur = cur->next;
		}
		//构建新链表的next和random
		while(cur!=nullptr){
			map[cur]->next = map[cur->next];
			map[cur]->random = map[cur->random];
			cur = cur->next;
		}
		//返回新链表的头节点
		return map[head];
	}
};

unordered_map用法参考链接:
链接:参考力扣题解
来源:力扣(LeetCode)

你可能感兴趣的:(力扣刷题,链表,数据结构)