剑指Offer:复杂链表的复制(Java版)

tech2022-11-29  102

题目:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

对于这道题,分三个步骤去考虑,① 遍历链表,将每个结点进行复制,并插入到该结点的后面

② 再次遍历链表,将每个原始结点的随机指针赋值给新结点

③ 将链表拆分为原始链表和新结点的链表

代码如下:

public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } public RandomListNode Clone(RandomListNode pHead) { if (pHead == null) { return null; } // 遍历链表,复制每个结点,每个复制的结点插入到被复制结点的后面 RandomListNode currentNode = pHead; while (currentNode != null) { RandomListNode copyNode = new RandomListNode(currentNode.label); RandomListNode nextNode = currentNode.next; currentNode.next = copyNode; copyNode.next = nextNode; currentNode = nextNode; } // 再次遍历链表,将老结点的随机指针复制给copyNode currentNode = pHead; while (currentNode != null) { if (currentNode.random == null) { currentNode.next.random = null; } else { //这里之所以是currentNode.random.next,是因为如果写currentNode.random的话,这还是原始链表的结点 //由于第一步已经将链表中所有结点都复制了一遍,并且新结点是插入在老结点后面的,所以currentNode.random // 实际和currentNode.random.next是相同的,只是currentNode.random.next是新复制的结点而已 currentNode.next.random = currentNode.random.next; } currentNode = currentNode.next.next; } // 拆分链表,把链表分为原链表和复制后的链表 currentNode = pHead; RandomListNode newHead = pHead.next; while (currentNode != null) { RandomListNode copyNode = currentNode.next; currentNode.next = copyNode.next; if (copyNode.next == null) { copyNode.next = null; } else { copyNode.next = copyNode.next.next; } currentNode = currentNode.next; } return newHead; }

 

最新回复(0)