Back to DSA

Reverse Linked List

easy
Acceptance: 69%
Linked List

Take a singly linked list and reverse the direction of every link so that the last node becomes the new head and the original head becomes the tail. Return the new head of the reversed list.

Examples

Example 1:
Input:head = [10,20,30,40]
Output:[40,30,20,10]
Example 2:
Input:head = [7,3]
Output:[3,7]

Hints

00:00
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null, curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}
Time complexityO(n)
Space complexityO(1)