• 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 }
  • 相关阅读:
    用YSLOW分析页面速度
    字节与字符的区别
    五小步大幅提高firefox页面加载速度【转载】
    Asp.netUpload(大文件上传) 终于找到一个可以用的了
    (续), 这个是我比较满意的
    共享一些变态的签名,希望不太OLD
    C#入门代码
    最后是所有的附件和一些他们的文章
    JavaScript日期处理函数大全
    加密解密Url的类
  • 原文地址:https://www.cnblogs.com/zle1992/p/7689517.html
Copyright © 2020-2023  润新知