Iterative solution using 3 pointers.
class ListNode {
ListNode next;
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while (curr != null) {
next = curr.next;
curr.next = prev; // changes arrow direction
prev = curr;
curr = next;
}
return prev;
}
}
- Time Complexity: O(n)
- Space Complexity: O(1)