Example 2: Clone a Linked List
The ptr
pointer is used only in the special case where it is null
. The tail
pointer is then used in the standard way to create copies after the special case is done.
The idea is to iterate over the original linked list
and maintain 2 pointers, ptr
and tail
to keep track of the new linked list.
xxxxxxxxxx
47
print(cloned);
function cloneList(head) {
let current = head;
let newPointer = null;
let tail = null;
​
while (current != null) {
if (newPointer == null) {
newPointer = new Node(current.val, null);
tail = newPointer;
} else {
tail.next = new Node(current.val, null);
tail = tail.next;
}
current = current.next;
}
return newPointer;
}
​
function print(head) {
let finalStr = "";
let current = head;
while (current != null) {
finalStr += current.val + " -> ";
current = current.next;
}
finalStr += "null";
console.log(finalStr);
}
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment