Easy
Given the head
of a singly linked list, reverse the list, and return the reversed list.
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: []
Constraints:
[0, 5000]
.-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
#include <stdio.h>
#include <stdlib.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
// Function to reverse a linked list
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL; // Pointer to the previous node
struct ListNode* curr = head; // Pointer to the current node
while (curr != NULL) {
struct ListNode* next = curr->next; // Store the next node
curr->next = prev; // Reverse the current node's pointer
prev = curr; // Move prev to the current node
curr = next; // Move to the next node
}
return prev; // New head of the reversed list
}