leetCode解题报告之Copy List with Random Pointer
来源:互联网 发布:cda数据分析师怎么考证 编辑:程序博客网 时间:2024/05/16 16:01
题目:
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.
分析:我们知道如果是简单的copy List 的话,那么我们只需要从头到尾遍历下来,new出对应个数的Node,并把它们的连接关系设置好就可以了,但是这道题目中每个节点Node出现了Random属性,也就意味着可能当前结点Node所依赖的那个Random对应的结点还没有被创建出来。
解题思路:
为了解决“分析”里提到的问题,我们需要做如下三步处理!
1. 在OldList中的每个结点后,插入一个CopyNode,这个结点的Random域和Next域与OldList中的被拷贝Node的Random域和Next一致,然后让被拷贝结点的Next域指向CopyNode结点,这样先创建出OldList中结点对应的CopyNode结点。
2. 由于所有的CopyNode都已经创建出来了,我们就可以调整这些CopyNode真正的Random域的值了。
3. 调整所有CopyNode的Next域的值,恢复OldList所有Node的Next的值到初始状态!
图解:
AC代码:
package copylist;class RandomListNode { int label; RandomListNode next, random; RandomListNode(int x) { this.label = x; }};public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) return head; /*第一步:在OldList的每个节点后面都插入一个copyNode(拷贝链表的结点)*/ RandomListNode nowNode = head; while (nowNode != null){ RandomListNode copyNode = new RandomListNode(nowNode.label); copyNode.random = nowNode.random; copyNode.next = nowNode.next; nowNode.next = copyNode; nowNode = nowNode.next.next; } /*第二步:确定NewList的每个节点,真正关联到的Random结点是哪个, * 因为第一步已经把所有NewList上的结点都建立了*/ nowNode = head; while (nowNode != null){ if (nowNode.random != null){ nowNode.next.random = nowNode.random.next; } nowNode = nowNode.next.next; } /*第三步:还原OldList的next为一开始的next结点 * 并拼接NewList的next到它真正所应该关联的next结点 * 即:保持老链表OldList不变,拼接新链表NewList! * */ RandomListNode pHead = new RandomListNode(0); pHead.next = head; RandomListNode newlist = pHead; nowNode = head; while (nowNode != null){ pHead.next = nowNode.next; nowNode.next = pHead.next.next; pHead = pHead.next; nowNode = nowNode.next; } return newlist.next; }}
0 0
- leetCode解题报告之Copy List with Random Pointer
- LeetCode — Copy List with Random Pointer 解题报告
- 【LeetCode】Copy List with Random Pointer 解题报告
- LeetCode 解题报告 Copy List With Random Pointer
- [leetcode] 138. Copy List with Random Pointer 解题报告
- [Leetcode] 138. Copy List with Random Pointer 解题报告
- [leetcode]138. Copy List with Random Pointer@Java解题报告
- Copy List with Random Pointer解题报告
- Copy List with Random Pointer 解题报告
- LeetCode之Copy List with Random Pointer
- leetcode之Copy List with Random Pointer
- leetcode 之 Copy List with Random Pointer
- leetcode之Copy List with Random Pointer
- leetcode之Copy List with Random Pointer
- LeetCode之Copy List with Random Pointer
- LeetCode之Copy List with Random Pointer
- Copy List with Random Pointer的解题报告
- leetcode解题笔记-Copy List with Random Pointer
- IP包只有16位长度与流媒体帧分片的内在逻辑
- Android 安装教程
- Qt-文本绘制
- Erlang不能错过的盛宴
- WhatsApp背后的小众编程语言:Erlang
- leetCode解题报告之Copy List with Random Pointer
- 代码坏味及解决方案(底层重构和设计模式两个方面)
- NSRunLoop之夜
- 对于缓存的理解和分析。
- 连载:面向对象葵花宝典:思想、技巧与实践(7) - “对象”新解
- C# 委托实例(跨窗体操作控件)
- 黑马程序员_工具使用02_Xcode的快捷键及代码格式化
- C语言二叉树与队列实现基础代码
- RSHC PHP MVC框架編寫手記[2]