Reverse a linked list. Implement a function that reverses a singly linked list.
Anonymous
// Function to reverse a singly linked list ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; ListNode* next = nullptr; while (curr != nullptr) { 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; // prev will be the new head of the reversed list }
Check out your Company Bowl for anonymous work chats.