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

&nbsp;
Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]


Example 2:

Input: head = [1,2]
Output: [2,1]


Example 3:

Input: head = []
Output: []


&nbsp;
Constraints:


	The number of nodes in the list is the range [0, 5000].
	-5000 &lt;= Node.val &lt;= 5000


&nbsp;
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head==None or head.next==None:
            return head
        p = None
        while(head != None):
            temp = head.next
            head.next = p
            p = head
            head = temp
        return p
/**
 * 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; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {

        if(head == null || head.next == null) return head;

        ListNode curr = head;
        ListNode temp = null, next = curr.next;
        curr.next = null;

        while(curr !=null && next !=null)
        {
            // before cutting off link between next & its next, save next.next
            temp = next.next;
            // let next point to curr
            next.next = curr;

            curr = next;
            next = temp;

        }

        return curr;

    }
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL)
        {
            return head;
        }
        ListNode *s=reverseList(head->next);
        ListNode *t=head->next;
            t->next=head;
        head->next=NULL;
        return s;
        
    }
};
var reverseList = function(head) {
    
    //  Iteratively
    [cur, rev, tmp] = [head, null, null]
    while(cur){
        tmp = cur.next;
        cur.next = rev;
        rev = cur;
        cur = tmp;
        //[current.next, prev, current] = [prev, current, current.next]
    }
}
Reverse Linked List