Copy List with Random Pointer -- LeetCode

来源:互联网 发布:单机手游怎么修改数据 编辑:程序博客网 时间:2024/04/29 13:44
本思路是这样的,对链表进行三次扫描,第一次扫描对每个结点进行复制,然后把复制出来的新节点接在原结点的next,也就是让链表变成一个重复链表,就是新旧更替;第二次扫描中我们把旧结点的随机指针赋给新节点的随机指针,因为新结点都跟在旧结点的下一个,所以赋值比较简单,就是node.next.random = node.random.next,其中node.next就是新结点,因为第一次扫描我们就是把新结点接在旧结点后面。现在我们把结点的随机指针都接好了,最后一次扫描我们把链表拆成两个,第一个还原原链表,而第二个就是我们要求的复制链表。因为现在链表是旧新更替,只要把每隔两个结点分别相连,对链表进行分割即可。这个方法总共进行三次线性扫描,所以时间复杂度是O(n)。而这里并不需要额外空间,所以空间复杂度是O(1)。比起上面的方法,这里多做一次线性扫描,但是不需要额外空间,还是比较值的。实现的代码如下:

#include<iostream>using namespace std;#define STOP system("pause")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) return NULL;//1.intsert nodeRandomListNode* p_cur_node = head;while (p_cur_node){RandomListNode* tmp = new RandomListNode(p_cur_node->label);tmp->next = p_cur_node->next;p_cur_node->next = tmp;p_cur_node = tmp->next;}//2.insert random nodep_cur_node = head;while (p_cur_node){if (p_cur_node->random) p_cur_node->next->random = p_cur_node->random->next;else p_cur_node->next->random = nullptr;p_cur_node = p_cur_node->next->next;}//split thest two listRandomListNode* p_new_head = new RandomListNode(-1);RandomListNode* p_new_cur = p_new_head;p_cur_node = head;while (p_cur_node){p_new_cur->next = p_cur_node->next;p_new_cur= p_new_cur->next;p_cur_node->next = p_cur_node->next->next;p_cur_node = p_cur_node->next;}return p_new_head->next;}};int main(){RandomListNode* head = nullptr;Solution ss;ss.copyRandomList(head);STOP;return 0;}

0 0
原创粉丝点击