C++ Algorithm – Write a function to reverse a linked list
Given pointer to the head node of a linked list, the task is to reverse the linked list.
Examples:
Input : Head of following linked list
1->2->3->4->NULL
Output : Linked list should be changed to,
4->3->2->1->NULL
Input : Head of following linked list
1->2->3->4->5->NULL
Output : Linked list should be changed to,
5->4->3->2->1->NULL
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
[ad type=”banner”]
Iterative Method
Iterate trough the linked list. In loop, change next to prev, prev to current and current to next
C Programming:
Given linked list 85 15 4 20 Reversed Linked list 20 4 15 85
Time Complexity: O(n)
Space Complexity: O(1)
Recursive Method:
1) Divide the list in two parts - first node and rest of the linked list. 2) Call reverse for the rest of the linked list. 3) Link rest to first. 4) Fix head pointer

C++ Programming:
Time Complexity: O(n)
Space Complexity: O(1)
C++ Programming:
[ad type=”banner”]Output:
Given linked list 1 2 3 4 5 6 7 8 Reversed linked list 8 7 6 5 4 3 2 1


