/* // Definition for a Node. class Node { int val; Node next; Node random; public Node(int val) { this.val = val; this.next = null; this.random = null; } } */ class Solution { public Node copyRandomList(Node head) { if(head == null ) return null; Node curr = head; while(curr != null){ Node forward = curr.next; Node temp = new Node(curr.val); curr.next = temp; temp.next = forward; curr = forward; } curr = head; Node nh = head.next; //copying random pointers while(curr != null){ Node random = curr.random; if(random!=null) curr.next.random = random.next; curr = curr.next.next; } //organizing the linkedLists Node dummy = new Node(-1); curr = head; while(curr != null){ dummy.next = curr.next; curr.next = curr.next.next; dummy = dummy.next; curr = curr.next; } return nh; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter