Reverse a linked list!
Example 1
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
The classic interview question!
This question is deceptively simply. As I jokingly wrote above, this question is often used as an exemplary interview question. Because of this, let’s make sure we know it well :)
Time complexity
O(n)
Loop over every node in list.
Space complexity
O(n)
Extra list of seen
and new linked list of size n
.
Time complexity
O(n)
Loop over every node in list.
Space complexity
O(n)
Depth of recursive call / stack
Let’s be very careful with the pointers here! It helps to work this out with an example so let’s try the following:
Example
Input: 1->2->3
Output: 3->2->1
Time complexity
O(n)
Loop over every node in list.
Space complexity
O(1)
Depth of recursive call / stack
Quick Links
Legal Stuff