One Pager Cheat Sheet
- You need to write a
reverseListalgorithm that takes in aheadnode as a parameter and reverses a linked list of any length inO(n)time withO(1)space. - To reverse a linked list, simply
flipeach pointer, so that thenextreferences thepreviousnode. - It takes time and effort to properly
reversea linked list, so be sure to userecursionand draw diagrams to help keep your progress on track. - The general methodology for reversing a linked list involves a combination of
iterativeandrecursivetechniques that involve creating and manipulating 3 pointers:newHead,headandnextNode. - Keep track of the interview flow by using online comments or, if on a whiteboard,
diagramsto help visualize the sequence of events. Take advantage of the whiteboard to think through potential steps for reversing antechnical termlist, and then look at working code.- We will change the node's
nextreference to point to the previous node, usinghead.next = newHead;. - Storing the current node in
newHeadwill be used as thenextlater. - The right-side node is now
processedand has become the previous node. - We
store the node to the rightby settingnextNode = head.next;and repeat the same process with the next node. - We make the switch by setting the current node's
nexttonewHead, which is8. - We can
Seehow all the key concepts are put together in code, with lots of explaining comments! - The recursive approach to this can be tricky, especially on first glance, but most of the
magichappens when it reaches the end. - The
reverseListfunction is called on4, which reaches the termination clause due to there being no.next. 4was originally not pointing to anything, but afterhead.next.next = headit now points back to8.- We have achieved
O(n)linear time complexity andO(1)space complexity when traversing a linked list and reusing the old nodes.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx80
}var assert = require('assert');​// iterativefunction reverseList(head) { if (head.length < 2) { return; }​ let newHead = null; while (head != null) { let nextNode = head.next; head.next = newHead; newHead = head; head = nextNode; } return newHead;}​// recursivefunction reverseList(head) { if (!head || !head.next) { return head; }​ let rest = reverseList(head.next);​ head.next.next = head; delete head.next; return rest;}​function Node(val) {OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.


