[LeetCode]copy-list-with-random-pointer
Posted whl-shtudy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]copy-list-with-random-pointer相关的知识,希望对你有一定的参考价值。
题目: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.
题目理解:深拷贝一个带有random指针的链表,因为存在random指针故不能简单直接拷贝,要想让random指针指向正确的位置,必须链表中所有的节点都被复制好。也不能单独复制到一个新的链表,否则random指针也不能指向正确位置。
故考虑复制每个节点到原链表每个节点后面,然后将random指针指向正确位置后,把复制的节点剥离下来,形成新的链表即可。
代码:
1 public class Solution { 2 public RandomListNode copyRandomList(RandomListNode head) { 3 if(head == null) return head; 4 5 RandomListNode tmpList = head; 6 while(tmpList != null){ 7 RandomListNode node = new RandomListNode(tmpList.label); 8 node.next = tmpList.next; 9 tmpList.next = node; 10 11 tmpList = tmpList.next.next; 12 } 13 14 tmpList = head; 15 while(tmpList != null){ 16 if(tmpList.random != null)//这里的判断尤为重要,丢失的话会产生空指针的错误 17 tmpList.next.random = tmpList.random.next; 18 tmpList = tmpList.next.next; 19 } 20 RandomListNode pHead = new RandomListNode(0); 21 pHead.next = head; 22 RandomListNode newlist = pHead; 23 24 tmpList = head; 25 while (tmpList != null){ 26 pHead.next = tmpList.next; 27 tmpList.next = pHead.next.next; 28 pHead = pHead.next; 29 tmpList = tmpList.next; 30 } 31 return newlist.next; 32 } 33 }
重点:指针操作要注意可能产生空指针的错误。
以上是关于[LeetCode]copy-list-with-random-pointer的主要内容,如果未能解决你的问题,请参考以下文章