-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.cpp
More file actions
89 lines (70 loc) · 1.95 KB
/
linked_list.cpp
File metadata and controls
89 lines (70 loc) · 1.95 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
using namespace std;
struct Node {
int value;
Node* next;
Node(int val) : value(val), next(nullptr) {}
};
// Function to print the linked list
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
cout << current->value;
if (current->next != nullptr) {
cout << " -> ";
}
current = current->next;
}
cout << endl;
}
// Function to reverse the linked list iteratively
Node* reverseList(Node* head) {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;
while (current != nullptr) {
// Store the next node
next = current->next;
// Reverse the link
current->next = prev;
// Move pointers one position ahead
prev = current;
current = next;
}
// prev is now the new head
return prev;
}
// Function to create a linked list from an array
Node* createList(int arr[], int size) {
if (size == 0) return nullptr;
Node* head = new Node(arr[0]);
Node* current = head;
for (int i = 1; i < size; i++) {
current->next = new Node(arr[i]);
current = current->next;
}
return head;
}
// Function to delete the linked list to free memory
void deleteList(Node* head) {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
int main() {
// Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
Node* head = createList(arr, size);
cout << "Original linked list: ";
printList(head);
// Reverse the linked list
head = reverseList(head);
cout << "Reversed linked list: ";
printList(head);
// Clean up memory
deleteList(head);
return 0;
}