> [!META]- Inline Metadata > [tags:: #career #concepts/programming/linked-list] > [project group:: Neetcode 150] > [difficulty:: easy] > [status:: to begin] > [link:: https://leetcode.com/problems/reverse-linked-list/] > [up:: [[Leetcode MOC]]] ## Problem Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. **Example 1:** ![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg) **Input:** head = [1,2,3,4,5] **Output:** [5,4,3,2,1] **Example 2:** ![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg) **Input:** head = [1,2] **Output:** [2,1] **Example 3:** **Input:** head = [] **Output:** [] **Constraints:** - The number of nodes in the list is the range `[0, 5000]`. - `-5000 <= Node.val <= 5000` ## Solution ### Mine #### Python #### Rust ### LC's ## Things I Learned ## Scratchpad We should be able to do this in one pass. Maybe something like while head.next: next.next = head head = head.next? ### Neetcode Video #### Iterative Solution [[Two Pointer or Iterator Algorithm]] - prev (set to null), curr points at first. ![[Pasted image 20230110204003.png]] ```python def ... : prev, curr = None, head while curr: nxt = curr.next # Temp holder for next curr.next = prev # Set next attribute of current pointer to prev Node (reverse) prev = curr # Update prev pointer to point to current pointer curr = nxt # Update curr to point to what was originally curr.next ``` T $O(n)$, M $O(1)$ #### Recursive solution Takes M $O(N)$ because of recursive call ```python def ...: if not head: return None # base case new_head = head if head.next: new_head = self.reverseList(head.next) head.next.next = head # Reverse link between next node and head head.next = None return new_head ```