Question | Answer |
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. | public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return head; RandomListNode next, copy, iter = head; while(iter!=null){ next = iter.next; copy = new RandomListNode(iter.label); iter.next = copy; copy.next = next; iter = next; } iter = head; while(iter !=null){ if(iter.random != null){ iter.next.random = iter.random.next; } iter = iter.next.next; } RandomListNode pseudoHead = new RandomListNode(0); RandomListNode copyIter = pseudoHead; iter = head; while(iter!=null){ next = iter.next.next; copy = iter.next; copyIter.next = copy; copyIter = copy; iter.next = next; iter = next; } return pseudoHead.next; } |
There are no comments, be the first and leave one below:
Want to create your own Flashcards for free with GoConqr? Learn more.