Ninja technique🥷 to ACE DSA Interviews.
Given the head of a singly linked list, reverse the list, and return the reversed list.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL,*next=NULL,*curr=head;
while(curr!=NULL){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
return prev;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL) return NULL;
if(head->next==NULL) return head; // Make last node head
ListNode* newHead = reverseList(head->next);
head->next->next = head; // Actual reversal happens here
head->next = NULL;
return newHead;
}
};