创新工场笔试题Copy List with Random Pointer
2015-07-19 12:10
323 查看
假设有如下一个链表:
其中,random指向该链表的任意一个节点或者NULL,请编程实现该链表的深拷贝。
解析:把新节点插入到相应的旧节点后面:
分两步
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)
代码:
分两步
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)
代码:
Node *deepCopy (Node *head) { Node* now = head; Node* next = head->next; while( now != NULL ) { Node * copy = new Node; copy->value = now->value; copy->next = now->next; now ->next = copy; now = next; next = next->next; } now = head; while( now != NULL ) { now->next->random = now->random->next; now = now->next->next; } Node* head2 = head->next; Node* newHead = head->next; while( head2->next != NULL ) { head->next = head2->next; head2->next = head2->next->next; head = head->next; head2 = head2->next; } return newHead; }
相关文章推荐
- Docker之殇
- Error: org.apache.axis2.AxisFault at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) at 的原因
- Hadoop--hbase---练习13
- Hadoop—hbase安装----练习12
- Hadoop—HBase基础知识-----练习
- [转]网站重复请求解决方案
- Hadoop—Mahout部署及进行20newsgroup数据分析例子---练习10
- centos7安装xampp php环境包
- linux 计划任务
- 10934 - Dropping water balloons(DP)
- Hadoop—Pig部署及统计访问日志例子----练习8
- 每日回顾Shell —cat,tail,head
- 每天一个Linux命令-7(mount)
- nginx+iis实现负载均衡
- linux——samba服务器的配置
- 卸载 Apache方法
- Hadoop—MapReduce进行数据查询和实现推简单荐系统---练习7
- php学习记录之apache虚拟目录和虚拟主机
- Hadoop—在Eclipse中安装Hadoop插件及测试(Linux操作系统)--练习6
- HDU 1195 Open the Lock (双宽搜索)