Solution 1Iterative

  • TimeO(n)
  • SpaceO(1)

where, n is the number of nodes in the linked list.
Note: It's easier to code, once you draw the linked list and pointers to visualize the process.
LeetCode already has a good visualizer of the example, but in interviews, you can draw it on paper/whiteboard.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    '''
    Time Complexity: O(n)
    Space Complexity: O(1)
    where, n is the number of nodes in the linked list.
    Note: It's easier to code, once you draw the linked list and pointers to visualize the process.
    LeetCode already has a good visualizer of the example, but in interviews, you can draw it on paper/whiteboard.
    '''
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node = head
        oldNode = None
        while node:
            temp = node.next
            node.next = oldNode
            oldNode = node
            node = temp
        return oldNode
Leet Code/python.py · L982–1004
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}
Leet Code/java.java · L760–781