Reverse a Singly Linked List
Reverse the singly linked list and return the head of the reversed linked list.
Statement
Given the head of a singly linked list, reverse the linked list and return its new or updated head.
Example
Consider the following linked list:
Return the pointer to the reversed linked list as shown in the figure:
Sample input
[7, 14, 21, 28]
Expected output
[28, 21, 14, 7]
Try it yourself #
main.cpp
LinkedList.cpp
LinkedListNode.cpp
#include "LinkedList.cpp"using namespace std;LinkedListNode* Reverse(LinkedListNode* head) {//TODO: Write - Your - Code}
Solution 1
If the linked list only contains 0 or 1 node, then the current list can be returned as it is. If there are two or more nodes, then the iterative solution starts with two node pointers:
- First pointer: points to the head of the input linked list.
- Second pointer: It points to the head’s next node.
We then set the next
of the first pointer to ...
Access this course and 1400+ top-rated courses and projects.