Reverse Linked List

Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

LeetCode Problem - 206

class Solution {
    // Method to reverse a singly linked list
    public ListNode reverseList(ListNode head) {
        // Initializing variables to keep track of previous and current nodes
        ListNode prev = null;
        ListNode current = head;

        // Iterating through the list
        while(current != null){
            // Storing the next node temporarily
            ListNode temp = current.next;
            // Reversing the link of the current node
            current.next = prev;
            // Moving to the next node
            prev = current;
            current = temp;
        }
        // Returning the new head of the reversed list
        return prev;
    }
}