Now let's see this all put together in code, with lots of comments for edification!
xxxxxxxxxx44
console.log(l2);class LinkedListNode { constructor(val, next = null) { this.val = val; this.next = next; }}​l1 = new LinkedListNode(8);l2 = new LinkedListNode(4);l1.next = l2;​// start at head, 8let head = l1;// example: 8 -> 4let newHead = null;while (head) { /* FIRST PASS */ // store the node to the right let nextNode = head.next; // nextNode = 4, still 8 -> 4 // set the current node's next to point backwards head.next = newHead; // 8 -> null // store the current node, to be used as the new next later newHead = head; // newHead = 8 // the previously right-side node is now processed head = nextNode; // head = 4OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


