fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. struct Node {
  6. int data;
  7. Node* next;
  8.  
  9.  
  10. Node(int value) {
  11. data = value;
  12. next = nullptr;
  13. }
  14. };
  15.  
  16.  
  17. Node* createLinkedListFromArray(int arr[], int size) {
  18. if (size == 0) return nullptr; // If array is empty, return nullptr
  19.  
  20. // Create the head node
  21. Node* head = new Node(arr[0]);
  22. Node* current = head;
  23.  
  24.  
  25. for (int i = 1; i < size; i++) {
  26. current->next = new Node(arr[i]);
  27. current = current->next;
  28. }
  29.  
  30. return head;
  31. }
  32.  
  33.  
  34. void printLinkedList(Node* head) {
  35. Node* current = head;
  36. while (current != nullptr) {
  37. cout << current->data << " -> ";
  38. current = current->next;
  39. }
  40. cout << "nullptr" << endl;
  41. }
  42.  
  43. int main() {
  44. int arr[] = {10, 20, 30, 40, 50};
  45. int size = sizeof(arr) / sizeof(arr[0]);
  46.  
  47.  
  48. Node* head = createLinkedListFromArray(arr, size);
  49.  
  50.  
  51. printLinkedList(head);
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5260KB
stdin
Standard input is empty
stdout
10 -> 20 -> 30 -> 40 -> 50 -> nullptr