fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Node class definition
  6. class Node {
  7. public:
  8. int data;
  9. Node* next;
  10. Node(int x) : data(x), next(nullptr) {}
  11. };
  12.  
  13. class Solution {
  14. public:
  15. Node* constructLL(vector<int>& arr) {
  16. if (arr.empty()) return nullptr;
  17. Node* head = new Node(arr[0]);
  18. Node* tmp = head;
  19. for (int i = 1; i < arr.size(); i++) {
  20. tmp->next = new Node(arr[i]);
  21. tmp = tmp->next;
  22. }
  23. return head;
  24. }
  25. };
  26.  
  27. // Helper function to print linked list
  28. void printList(Node* head) {
  29. Node* current = head;
  30. while (current != nullptr) {
  31. cout << current->data;
  32. if (current->next != nullptr) {
  33. cout << " -> ";
  34. }
  35. current = current->next;
  36. }
  37. cout << endl;
  38. }
  39.  
  40. // Helper function to delete linked list (prevent memory leaks)
  41. void deleteList(Node* head) {
  42. while (head != nullptr) {
  43. Node* temp = head;
  44. head = head->next;
  45. delete temp;
  46. }
  47. }
  48.  
  49. int main() {
  50. Solution sol;
  51.  
  52. // Test Case 1: Normal case
  53. vector<int> arr1 = {1, 2, 3, 4, 5};
  54. Node* list1 = sol.constructLL(arr1);
  55. cout << "Test 1: ";
  56. printList(list1); // Output: 1 -> 2 -> 3 -> 4 -> 5
  57. deleteList(list1);
  58.  
  59. // Test Case 2: Empty vector
  60. vector<int> arr2 = {};
  61. Node* list2 = sol.constructLL(arr2);
  62. cout << "Test 2: ";
  63. if (list2 == nullptr) {
  64. cout << "Empty list (nullptr)" << endl;
  65. }
  66. deleteList(list2);
  67.  
  68. // Test Case 3: Single element
  69. vector<int> arr3 = {42};
  70. Node* list3 = sol.constructLL(arr3);
  71. cout << "Test 3: ";
  72. printList(list3); // Output: 42
  73. deleteList(list3);
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Test 1: 1 -> 2 -> 3 -> 4 -> 5
Test 2: Empty list (nullptr)
Test 3: 42