Use traditional linked list way, not efficient of course


  • 0
    S

    Indeed, this question can be using map, however, when i did this question as a mock interview, I used traditional linked list way to tackle the question. Not efficient.

    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
             if(head == null) {
                return null;
            }
            RandomListNode curOri = head;
            RandomListNode curNew = new RandomListNode(head.label);
            RandomListNode curNewHead = curNew;
            curOri = curOri.next;
            if(curOri == null) {
                if(head.random!=null) {
                    curNew.random = curNew;
                }
                return curNewHead;
            }
            while(curOri!=null) {
                curNew.next = new RandomListNode(curOri.label);
                curNew = curNew.next;
                curOri = curOri.next;
            }
            curOri = head;
            curNew = curNewHead;
            RandomListNode search = curNewHead;
            while(curOri!=null) {
                if(curOri.random!=null) {
                     int val = curOri.random.label;
                    while(search.label != val) {
                        search = search.next;
                    }
                    curNew.random = search;
                    search = curNewHead;
                
                }else {
                    curNew.random = null;
                }
                curOri = curOri.next;
                curNew = curNew.next;
             }
            return curNewHead;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.