leetCode解题报告之Copy List with Random Pointer

た 入场券 2022-08-26 01:22 325阅读 0赞

题目:

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的值到初始状态!

图解:

SouthEast

AC代码:

  1. package copylist;
  2. class RandomListNode {
  3. int label;
  4. RandomListNode next, random;
  5. RandomListNode(int x) { this.label = x; }
  6. };
  7. public class Solution {
  8. public RandomListNode copyRandomList(RandomListNode head) {
  9. if (head == null)
  10. return head;
  11. /*第一步:在OldList的每个节点后面都插入一个copyNode(拷贝链表的结点)*/
  12. RandomListNode nowNode = head;
  13. while (nowNode != null){
  14. RandomListNode copyNode = new RandomListNode(nowNode.label);
  15. copyNode.random = nowNode.random;
  16. copyNode.next = nowNode.next;
  17. nowNode.next = copyNode;
  18. nowNode = nowNode.next.next;
  19. }
  20. /*第二步:确定NewList的每个节点,真正关联到的Random结点是哪个,
  21. * 因为第一步已经把所有NewList上的结点都建立了*/
  22. nowNode = head;
  23. while (nowNode != null){
  24. if (nowNode.random != null){
  25. nowNode.next.random = nowNode.random.next;
  26. }
  27. nowNode = nowNode.next.next;
  28. }
  29. /*第三步:还原OldList的next为一开始的next结点
  30. * 并拼接NewList的next到它真正所应该关联的next结点
  31. * 即:保持老链表OldList不变,拼接新链表NewList!
  32. * */
  33. RandomListNode pHead = new RandomListNode(0);
  34. pHead.next = head;
  35. RandomListNode newlist = pHead;
  36. nowNode = head;
  37. while (nowNode != null){
  38. pHead.next = nowNode.next;
  39. nowNode.next = pHead.next.next;
  40. pHead = pHead.next;
  41. nowNode = nowNode.next;
  42. }
  43. return newlist.next;
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,325人围观)

还没有评论,来说两句吧...

相关阅读