题目描述

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

思路:

剑指:复杂链表的复制(转自牛客网讨论区)

 

package number29;

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

    RandomListNode(int label) {
        this.label = label;
    }
}
package number29;

public class Solution1 {//复杂链表的复制
	/*
	 * 一共分为三步:
	 * 1.按顺序复制每个节点,并将新节点加到原节点后,比如A->B,得到A->A1->B->B1
	 * 2.给复制后的节点的随机指针赋值
	 * 3.拆分链表
	 */
	public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead==null) {
        	return null;
        }
        RandomListNode cur = pHead;
        //1.按顺序复制每个节点,并将新节点加到原节点后,比如A->B,得到A->A1->B->B1
        while(cur != null) {
        	RandomListNode cloneNode = new RandomListNode(cur.label);
        	cloneNode.next = cur.next;
        	cur.next = cloneNode;
        	cur = cloneNode.next;
        }
        cur = pHead;//重新指向头
        //2.给复制后的节点的随机指针赋值
        while(cur != null) {
        	cur.next.random = cur.random == null? null:cur.random.next;
        	cur = cur.next.next;//由A越过A1指向B
        }
        //3.拆分链表
        cur = pHead;//重新指向头
        RandomListNode pCloneHead = cur.next;//新链表表头
        while(cur!=null) {
        	RandomListNode cloneNode = cur.next;
        	cur.next = cloneNode.next;
        	cloneNode.next = cur.next==null? null:cur.next.next;
        	cur = cur.next;
        }
        return pCloneHead;
    }
	
}

 

相关文章:

  • 2021-08-29
  • 2021-07-03
  • 2021-11-17
  • 2021-10-16
  • 2021-11-17
  • 2021-12-28
  • 2018-04-07
  • 2021-09-29
猜你喜欢
  • 2018-07-08
  • 2021-05-27
  • 2021-09-14
  • 2021-08-16
  • 2019-11-25
  • 2019-09-06
  • 2021-04-03
相关资源
相似解决方案