Leetcode232: Copy List with Random Pointer
来源:互联网 发布:windows rt 编辑:程序博客网 时间:2024/05/10 14:35
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.
网上看到一个O(n)的算法,非常巧妙的利用了原来链表的信息:
该算法更为巧妙,不用保存原始链表的映射关系,构建新节点时,指针做如下变化,即把新节点插入到相应的旧节点后面:
同理分两步
1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next
2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next
该算法时间复杂度O(N),空间复杂度O(1)
/** * 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 *pos1 = head, *pos2 = head->next; while(pos1 != NULL) { pos1->next = new RandomListNode(pos1->label); pos1->next->next = pos2; pos1 = pos2; if(pos2!= NULL) pos2 = pos2->next; } pos1 = head; pos2 = head->next; while(pos1!=NULL) { if(pos1->random==NULL) pos2->random=NULL; else { pos2->random = pos1->random->next; } pos1 = pos1->next->next; if(pos2->next!=NULL) pos2 = pos1->next; } RandomListNode *res = head->next; pos1 = head; pos2 = head->next; while(pos2->next!=NULL) { pos1->next = pos2->next; pos1 = pos2; if(pos2->next!=NULL) pos2=pos2->next; } pos1->next=NULL; pos2->next=NULL; return res; }};
0 0
- Leetcode232: Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- 130 js javascrtipt DOM编程艺术1~6章
- Linux中Mysql的安装和配置方法
- SqlServer按半小时分组统计
- sqllite 自动增长列
- Eclipse 保存文件时自动格式化代码
- Leetcode232: Copy List with Random Pointer
- 在Linux服务器建立小团队Git服务
- poi报表技术快速入门demo(带图片插入)
- 【第十章】集成其它Web框架 之 10.2 集成Struts1.x ——跟我学spring3
- SecureCRT 破解安装
- 2016年贴一篇我2013年的文章写我国外出差的经历
- Facebook Patch for Dalvik
- java 添加水印文字和图片
- css样式学习笔记七