Given the head of a singly linked list, reverse the list, and return the reversed list.
?
Input head = [1,2,3,4,5]
Output [5,4,3,2,1]
Input head = [1,2]
Output [2,1]
Input head = []
Output []
From: LeetCode
Link: 206. Reverse Linked List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *prev = NULL;
struct ListNode *curr = head;
struct ListNode *next = NULL;
while (curr != NULL) {
next = curr->next; // Store next node
curr->next = prev; // Reverse current node's pointer
prev = curr; // Move pointers one position ahead
curr = next;
}
head = prev; // Update head to new first node
return head;
}