N25_复杂链表的复制

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路:
*1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
*2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
*3、拆分链表,将链表拆分为原链表和复制后的链表

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
      	//1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
		if(pHead==null) {return null;}
		RandomListNode c=pHead;  //指针指向当前节点
		while(c!=null) {
			RandomListNode clone=new RandomListNode(c.label);
			clone.next=c.next;
			clone.random=null;
            c.next=clone;
			c=clone.next;
		}
		
		//2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
		c=pHead;
		while(c!=null) {
			RandomListNode clone=c.next;
			if(c.random!=null) {
				clone.random=c.random.next;
			}
			c=clone.next;
		}
		
		//3拆分链表,将链表拆分为原链表和复制后的链表
		c=pHead;
		RandomListNode cloneHead=pHead.next;
		while(c!=null) {
			RandomListNode clone=c.next;
			c.next=clone.next;
			if(clone.next==null) clone.next=null;
			else {clone.next=c.next.next;}
			c=c.next;
		}
		
		
		return cloneHead;
    }
}

  

posted @ 2019-07-04 10:54  柯汐  阅读(126)  评论(0编辑  收藏  举报