还是得多做题,细节的地方老出错误。
解题思路:
/** * @Author: Allen * @Version:v1.00 * @CreateData: * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点, * 另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。 * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) */ public class FuZaLianBiaoDeFuZhi { public static void main(String[] args) { RandomListNode headListNode = new RandomListNode(1); headListNode.next = new RandomListNode(2); headListNode.random = headListNode.next; Solution19 solution19 = new Solution19(); RandomListNode head = solution19.Clone(headListNode); } } class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } class Solution19 { public RandomListNode Clone(RandomListNode pHead) { if(pHead==null){ return null; } RandomListNode clonedHead = null; RandomListNode pListHead = null; pListHead = CloneNode(pHead); pListHead = makeRandomIndex(pListHead); clonedHead = splitList(pListHead); return clonedHead; } //1.复制每个节点,将每个复制的节点放置于被复制的节点后面 private RandomListNode CloneNode(RandomListNode pHead){ RandomListNode pNode = pHead; while(pNode!=null){ RandomListNode clonedNode = new RandomListNode(pNode.label); clonedNode.next=pNode.next; pNode.next=clonedNode; pNode=clonedNode.next; } return pHead; } //2.为每个复制的节点的random引用赋值,其值是原来节点的random引用的下一个节点 private RandomListNode makeRandomIndex(RandomListNode pHead){ RandomListNode pNode = pHead; while(pNode!=null){ RandomListNode clonedNode = pNode.next; if(pNode.random!=null)//报空指针了,节操何在 clonedNode.random = pNode.random.next; pNode = clonedNode.next; } return pHead; } //3.拆分链表 private RandomListNode splitList(RandomListNode pHead){ RandomListNode pNode = pHead; RandomListNode clonedHead = null; RandomListNode clonedNode = null; if(pNode!=null){ clonedHead = pHead.next; clonedNode = clonedHead; pNode.next = clonedNode.next; pNode = clonedNode.next; } while(pNode!=null){ clonedNode.next = pNode.next; clonedNode = clonedNode.next; pNode.next = clonedNode.next; pNode = pNode.next; } return clonedHead; } }