fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Node structure for doubly linked list
  6. struct Node {
  7. int data;
  8. Node* next;
  9. Node* prev;
  10. Node(int x) : data(x), next(nullptr), prev(nullptr) {}
  11. };
  12.  
  13. class Solution {
  14. public:
  15. Node* constructDLL(vector<int>& arr) {
  16. if(arr.empty()) return nullptr;
  17.  
  18. Node* head = new Node(arr[0]);
  19. Node* prev = nullptr;
  20. Node* current = head;
  21.  
  22. for(int i = 1; i < arr.size(); i++) {
  23. current->next = new Node(arr[i]);
  24. current->next->prev = current;
  25. current = current->next;
  26. }
  27.  
  28. return head;
  29. }
  30. };
  31.  
  32. // Helper function to print DLL forward
  33. void printForward(Node* head) {
  34. Node* current = head;
  35. while(current) {
  36. cout << current->data;
  37. if(current->next) cout << " <-> ";
  38. current = current->next;
  39. }
  40. cout << endl;
  41. }
  42.  
  43. // Helper function to print DLL backward
  44. void printBackward(Node* tail) {
  45. Node* current = tail;
  46. while(current) {
  47. cout << current->data;
  48. if(current->prev) cout << " <-> ";
  49. current = current->prev;
  50. }
  51. cout << endl;
  52. }
  53.  
  54. // Helper function to delete DLL
  55. void deleteDLL(Node* head) {
  56. while(head) {
  57. Node* temp = head;
  58. head = head->next;
  59. delete temp;
  60. }
  61. }
  62.  
  63. int main() {
  64. Solution sol;
  65.  
  66. // Test Case 1: Normal case
  67. vector<int> arr1 = {1, 2, 3, 4, 5};
  68. Node* dll1 = sol.constructDLL(arr1);
  69. cout << "Test 1 - Forward: ";
  70. printForward(dll1);
  71.  
  72. // Get tail to test backward traversal
  73. Node* tail1 = dll1;
  74. while(tail1->next) tail1 = tail1->next;
  75. cout << "Test 1 - Backward: ";
  76. printBackward(tail1);
  77. deleteDLL(dll1);
  78.  
  79. // Test Case 2: Single element
  80. vector<int> arr2 = {10};
  81. Node* dll2 = sol.constructDLL(arr2);
  82. cout << "\nTest 2 - Forward: ";
  83. printForward(dll2);
  84. cout << "Test 2 - Backward: ";
  85. printBackward(dll2); // Same as forward for single node
  86. deleteDLL(dll2);
  87.  
  88. // Test Case 3: Empty list
  89. vector<int> arr3 = {};
  90. Node* dll3 = sol.constructDLL(arr3);
  91. cout << "\nTest 3 - Empty list: ";
  92. printForward(dll3); // Should print nothing
  93. deleteDLL(dll3);
  94.  
  95. return 0;
  96. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Test 1 - Forward: 1 <-> 2 <-> 3 <-> 4 <-> 5
Test 1 - Backward: 5 <-> 4 <-> 3 <-> 2 <-> 1

Test 2 - Forward: 10
Test 2 - Backward: 10

Test 3 - Empty list: