Reverse a linked list.
Example 1:
Input:
10 20 30 40
Output: 40->30->20->10
Example 2:
Input:
10 20 30 40 50
Output: 50->40->30->20->10
1. Node Structure:-
The code defines a struct Node to represent individual elements of the singly linked list.
Each node contains two components: an integer data and a pointer next.
The data component stores the value of the node.
The next component is a pointer to the next node in the list.
2. Reverse Linked List Function:-
The reverseLinkedList function takes the head of a linked list as input and returns the head of the reversed
linked list.
Inside the function, three pointers are used: prev, current, and next.
A prev pointer is initialized to nullptr to serve as the previous node of the current node.
The current pointer is initialized to the head of the original linked list.
A next pointer is used to store the next node in the original linked list temporarily.
The function iterates through the linked list and reverses the direction of the pointers to change the order
of the nodes.
3. Main Function:-
Inside the main function, a linked list is created with nodes containing values 10, 20, 30, and 40.
The linked list is connected by setting the next pointers.
The reverseLinkedList function is called to reverse the linked list, and the returned head is assigned to
head.
The reversed linked list is then printed by iterating through it.
4. Output:-
The program prints the reversed linked list in the form of a sequence of values separated by "->" (e.g.,
"40->30->20->10").