#include <iostream>
#include <vector>
using namespace std;
// Node class definition
class Node {
public:
int data;
Node* next;
Node(int x) : data(x), next(nullptr) {}
};
class Solution {
public:
Node* constructLL(vector<int>& arr) {
if (arr.empty()) return nullptr;
Node* head = new Node(arr[0]);
Node* tmp = head;
for (int i = 1; i < arr.size(); i++) {
tmp->next = new Node(arr[i]);
tmp = tmp->next;
}
return head;
}
};
// Helper function to print linked list
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
cout << current->data;
if (current->next != nullptr) {
cout << " -> ";
}
current = current->next;
}
cout << endl;
}
// Helper function to delete linked list (prevent memory leaks)
void deleteList(Node* head) {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
int main() {
Solution sol;
// Test Case 1: Normal case
vector<int> arr1 = {1, 2, 3, 4, 5};
Node* list1 = sol.constructLL(arr1);
cout << "Test 1: ";
printList(list1); // Output: 1 -> 2 -> 3 -> 4 -> 5
deleteList(list1);
// Test Case 2: Empty vector
vector<int> arr2 = {};
Node* list2 = sol.constructLL(arr2);
cout << "Test 2: ";
if (list2 == nullptr) {
cout << "Empty list (nullptr)" << endl;
}
deleteList(list2);
// Test Case 3: Single element
vector<int> arr3 = {42};
Node* list3 = sol.constructLL(arr3);
cout << "Test 3: ";
printList(list3); // Output: 42
deleteList(list3);
return 0;
}