LintCode:M-复制带随机指针的链表
来源:互联网 发布:李晨璐 数据 编辑:程序博客网 时间:2024/06/05 23:53
LintCode:Link
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
样例
挑战
可否使用O(1)的空间
/** * 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) { //遍历链表,根据next复制节点,并将复制的节点插入复制节点的下一个位置 //变成原->新->原->新->原->新->null样子 RandomListNode node = head; while(node!=null){ RandomListNode newNode = new RandomListNode(node.label); RandomListNode tmp = node.next; node.next = newNode; newNode.next = tmp; node = tmp; } //遍历新链表,复制randow指针关系 //newNode的randow是其原节点指向的random的下一个(根据上面插入的特性,每个新节点跟在原节点后面) //然后删除旧节点 RandomListNode newHead = head.next; RandomListNode preNode = new RandomListNode(0); node = head; while(node!=null){ RandomListNode newNode = node.next; newNode.random = node.random==null?null:node.random.next; node = newNode.next; preNode.next = newNode; preNode = newNode; } return newHead; }}
阅读全文
0 0
- LintCode(M) 复制带随机指针的复杂链表
- LintCode:M-复制带随机指针的链表
- LintCode复制带随机指针的链表
- LintCode(105) 复制带随机指针的链表
- LintCode:复制带随机指针的链表
- lintcode,复制带随机指针的链表
- lintcode,复制带随机指针的链表
- LintCode 105-复制带随机指针的链表
- Lintcode: 复制带随机指针的链表
- lintcode 复制带随机指针的链表(105)
- 复制带随机指针的链表-LintCode
- [LintCode]105.复制带随机指针的链表
- LintCode-剑指Offer-(105)复制带随机指针的链表
- [LintCode] 复制带随机指针的链表 Copy List with Random Pointer
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- contourArea函数调用注意问题
- Shiro添加自己的Filter
- jquery onclick获取当前对象
- 如何获取spring的beans.xml的内容
- Hibernate与 MyBatis的比较
- LintCode:M-复制带随机指针的链表
- iOS开发之开源项目链接
- 路径替换小脚本
- 1084: [SCOI2005]最大子矩阵
- ArrayList 删除指定值
- c++为什么没有finaly,如何保证exception-safe?
- 解决:FreeChart图形中文乱码问题
- Spark RDD API
- c++调用java