题目:复制带随机指针的链表
来源:互联网 发布:乐知英语待遇 编辑:程序博客网 时间:2024/04/20 13:21
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
您在真实的面试中是否遇到过这个题?
Yes
样例
挑战
可否使用O(1)的空间
标签 Expand
相关题目 Expand
解题思路:http://blog.csdn.net/ljiabin/article/details/39054999
看似普通的链表操作,只是多了一个随机指针。
但是在遍历深度拷贝时候,会出现随机指针并不存在的情况,这就无法去指向随机指针。
但是可以用下面这种方式
--------------------------------------|
1.原始链表:1-------> 2 ------->3---------->4----------->5
-----------------------^
红色表示random指针。
2.在原始链表后复制原始链表的节点:
--------------------------------------------------------------------------------------------|
1-------> 1------->2---------->2----------->3---------> 3-------> 4 ------->4---------->5----------->5
--------------------------------------------------^
3. 复制原始链表的random指针
cur.next.random = cur.random.next;
------------------------------------------------------------------------------|
-------------------------------------------------------------------------------|
1-------> 1 ------->2---------->2----------->3 ---------> 3-------> 4 ------->4---------->5----------->5
--------------------------------------------------^
----------------------------------------------------^
4.将新旧链表的节点分离。
/*** Definition for singly-linked list with a random pointer.* class RandomListNode {* int label;* RandomListNode next, random;* RandomListNode(int x) { this.label = x; }* };*/public class Solution { /** * @param head: The head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */ public RandomListNode copyRandomList(RandomListNode head) { // write your code here if(null==head) return null; /*复制原始链表*/ RandomListNode cur = head; while(null!=cur){ RandomListNode newcur = new RandomListNode(cur.label); newcur.next = cur.next; cur.next = newcur; cur = cur.next.next; } /**复制链表的random指针**/ cur = head; while(null!=cur){ if(null!=cur.random){ cur.next.random = cur.random.next; } cur = cur.next.next; } /**拆分新旧链表**/ cur = head; RandomListNode newhead = head.next; while(null!=cur){ RandomListNode newcur = cur.next; if(null!=newcur){ cur.next = newcur.next; } if (newcur.next != null) newcur.next = newcur.next.next; cur = cur.next; } return newhead; }}
0 0
- 题目:复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 带随机指针的链表复制问题
- M1: 复制带随机指针的链表
- 复制一个带随机指针的链表
- LintCode复制带随机指针的链表
- LintCode(105) 复制带随机指针的链表
- LintCode:复制带随机指针的链表
- lintcode,复制带随机指针的链表
- lintcode,复制带随机指针的链表
- LintCode(M) 复制带随机指针的复杂链表
- LintCode 105-复制带随机指针的链表
- IOS工具篇
- 数据结构之树
- C++中头文件(.h)和源文件(.cpp)都应该写些什么
- Linux下的一些I/O统计工具
- 洛谷1220关路灯
- 题目:复制带随机指针的链表
- Java Log4j配置说明
- 学习笔记02
- *LeetCode-Combination Sum
- 解决axis2处理java.util.Date类型对象时丢弃时间部分的问题
- JSON与XML的区别比较
- ViewPager的使用简单记录
- 使用gitk的时候中文显示乱码的问题
- 题目:子集