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 }
  • 相关阅读:
    flask的Request对象
    Spinner实现列表下拉功能
    ListView用法
    DatePickerDialog和TimePickerDialog(基于对话框显示时间和日期)
    DataPicker以及TimePicker显示时间和日期(屏幕上显示)
    Floyd-Warshall算法(最短路)
    Bellman-Ford算法(最短路)
    前向星
    css3变形与动画
    CSS3背景 background-size
  • 原文地址:https://www.cnblogs.com/zle1992/p/7689517.html
Copyright © 2011-2022 走看看