-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList_Reverse_via_iteration.cpp
51 lines (41 loc) · 1.27 KB
/
LinkedList_Reverse_via_iteration.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
class ListNode {
public:
int val;
ListNode* next;
ListNode(int val) : val(val), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* current = head;
while (current != nullptr) {
ListNode* nextNode = current->next; // Store the next node.
current->next = prev; // Reverse the next pointer.
prev = current; // Move prev to the current node.
current = nextNode; // Move current to the stored next node.
}
return prev; // prev is now the new head of the reversed list.
}
// Helper function to print the linked list.
void printList(ListNode* head) {
while (head != nullptr) {
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
}
int main() {
// Creating a linked list: 1 -> 2 -> 3 -> 4 -> 5
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
std::cout << "Original linked list: ";
printList(head);
// Reversing the linked list.
head = reverseList(head);
std::cout << "Reversed linked list: ";
printList(head);
return 0;
}