zoukankan      html  css  js  c++  java
  • 138. 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.

    剑指offer 26题

    分三步:

      第一步:复制结点,复制的结点放在待复制的结点后,依然组成一个单链表 
      第二步:串接随机指针 
      第三步:将原单链表与复制链表拆开 

     1 public class Solution {
     2     public RandomListNode copyRandomList(RandomListNode head) {
     3         if(head==null) return head;
     4         copyNode(head);
     5         connectNode(head);
     6         return splitNode(head);
     7         
     8     }
     9     
    10     
    11     public void copyNode(RandomListNode head){
    12         RandomListNode node = head;
    13         while(node !=null){
    14             RandomListNode copyNode = new RandomListNode(node.label);
    15             copyNode.next = node.next;
    16             node.next = copyNode;
    17             node = copyNode.next;
    18         }
    19     }
    20     
    21     public void connectNode(RandomListNode head){
    22         RandomListNode node = head;
    23         while(node != null){
    24             if(node.random!=null)
    25                 node.next.random = node.random.next;
    26             node = node.next.next;
    27         }
    28         
    29     }
    30     
    31     public RandomListNode splitNode(RandomListNode head){
    32         RandomListNode copyhead = head.next;
    33         RandomListNode node = head;
    34         RandomListNode copynode ;
    35         
    36         while(node != null){
    37             copynode = node.next;
    38             node.next = copynode.next;
    39         
    40             if(node.next!= null)
    41                 copynode.next = node.next.next;
    42     
    43             node = node.next;
    44         }
    45         return copyhead;
    46     }
    47     
    48 }
  • 相关阅读:
    codeforces 1065F Up and Down the Tree
    初探莫比乌斯反演
    IOI2008 island
    miller——rabin判断素数
    NOIP2018游记
    NP是什么意思?
    word2016如何英汉互译
    2.1数字图像化
    Windows程序内部运行机制
    2.2图像灰度直方图
  • 原文地址:https://www.cnblogs.com/zle1992/p/7689517.html
Copyright © 2011-2022 走看看