剑指offer--26.复杂链表的复制

题目:实现一个函数复制一个复杂链表。在复杂链表中,每个结点除了有一个next指针指向下一个结点之外,还有一个random指针指向链表的任意结点或者null

分析:有很多思路,剑指offer都有讲解。最优思路是分为三步,第一步,复制原始链表的任意结点N并创建新结点N',再把N'连接到N的后面;第二步,设置复制出来的结点的random指针;第三步,将长链表拆分为两个链表

public class wr26copyList {
	public RandomListNode Clone(RandomListNode pHead){
		if(pHead==null){
			return null;
		}
		RandomListNode curNode=pHead;
//		第一步,复制原始链表的任意结点N并创建新结点N',再把N'链接到N的后面
		while(curNode!=null){
			RandomListNode cloneNode=new RandomListNode(curNode.label);
			cloneNode.next=curNode.next;
			curNode.next=cloneNode;
			curNode=cloneNode.next;
		}
//		第二步,设置复制出来的结点的random指针
		curNode=pHead;
		while(curNode!=null){
			if(curNode.random!=null){
				curNode.next.random=curNode.random.next;
			}
			curNode=curNode.next.next;
		}
//		第三步,将长链表拆分为两个链表
		curNode=pHead;
		RandomListNode cloneHead=pHead.next;
		RandomListNode cur=cloneHead;
		while(curNode!=null){
			curNode.next=curNode.next.next;
			if(cur.next!=null){
				cur.next=cur.next.next;
			}
			cur=cur.next;
			curNode=curNode.next;
		}
		return cloneHead;
	}

}


猜你喜欢

转载自blog.csdn.net/autumn03/article/details/80313811
今日推荐