
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。
我的解答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
/* public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null;
RandomListNode(int label) { this.label = label; } } */ import java.util.ArrayList; public class Solution { public RandomListNode Clone(RandomListNode pHead) { if (null == pHead) { return null; } ArrayList<RandomListNode> randomNodes = new ArrayList<>(); RandomListNode cloneHead = new RandomListNode(pHead.label); if (null != pHead.random) { RandomListNode random = new RandomListNode(pHead.random.label); randomNodes.add(random); cloneHead.random = random; } RandomListNode prev = cloneHead; while(null != pHead.next) { pHead = pHead.next; RandomListNode random = null; if (null != pHead.random) { random = new RandomListNode(pHead.random.label); randomNodes.add(random); } RandomListNode curNode = findInRandomList(randomNodes, pHead); if (null == curNode) { curNode = new RandomListNode(pHead.label); } prev.next = curNode; curNode.random = random; prev = curNode; } return cloneHead; } private RandomListNode findInRandomList(ArrayList<RandomListNode> randomNodes, RandomListNode node) { RandomListNode result = null; for (RandomListNode n : randomNodes) { if (n.label == node.label) { result = n; break; } } if (null != result) { randomNodes.remove(result); } return result; } }
|
近期评论