Fundamentals · Medium · Free
Reverse a singly linked list iteratively and recursively.
FresherFundamentalsData Structures & Algorithms
Reverse linked list
Iterative: three pointers prev/cur/next. Recursive: reverse rest, then fix head.
java
ListNode reverse(ListNode head) {
ListNode prev = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}Draw 3 nodes—pointer flip is a common whiteboard question.