复杂链表的复制(复制含有随机指针节点的链表)

来源:互联网 发布:c语言指针和引用 编辑:程序博客网 时间:2024/05/20 23:38

程序员代码面试指南(左程云)读书笔记

 第三章

复杂链表的复制(复制含有随机指针节点的链表)
题目:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
public class ListRandom {
 class RandomListNode {
        int label;
        RandomListNode next = null;
        RandomListNode random = null;

        RandomListNode(int label) {
            this.label = label;
        }
    }
方法一:
      用哈希表,将链表遍历一遍,key和value的值对应关系如下

然后再遍历一次链表,设置复制链表的next和random指针
  public RandomListNode Clone2(RandomListNode pHead)
        {
          HashMap<RandomListNode, RandomListNode> map=new HashMap<RandomListNode, RandomListNode>();
          RandomListNode cur=pHead;
          while(cur!=null){
              map.put(cur, new RandomListNode(cur.label));
              cur=cur.next;
          }
          cur=pHead;
          while(cur!=null){
              map.get(cur).next=map.get(cur.next);
              map.get(cur).random=map.get(cur.random);
              cur=cur.next;
          }
            return map.get(pHead);
        }
}


//方法二
   遍历一次链表,将链表复制的副本节点放到自己后面,再从左到右遍历一次链表,设置random指针。分离链表,返回。
package com.chen.zaixian.array;

import java.util.HashMap;



 public RandomListNode Clone(RandomListNode pHead) {
   if(pHead==null){return null;}
   RandomListNode cur=pHead;
   RandomListNode next=null;
   while(cur!=null){
       next=cur.next;
       cur.next=new RandomListNode(cur.label);
       cur.next.next=next;
       cur=next;
   }
   cur=pHead;
   RandomListNode curCopy=null;
   while(cur!=null){
       next=cur.next.next;
       curCopy=cur.next;
       curCopy.random=cur.random!=null?cur.random.next:null;
       cur=next;
   }
   RandomListNode res=pHead.next;
   cur=pHead;
   while(cur!=null){
       next=cur.next.next;
       curCopy=cur.next;
       cur.next=next;
       curCopy.next=next!=null?next.next:null;
       cur=next;
   }
     return res;
 } 

    
  
0 0