fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Define the Node structure
  5. struct Node {
  6. int data;
  7. Node* next;
  8. Node(int val) : data(val), next(nullptr) {}
  9. };
  10.  
  11. // Function to insert a new node at the end
  12. void insertAtEnd(Node*& head, int val) {
  13. Node* newNode = new Node(val);
  14. if (!head) {
  15. head = newNode;
  16. } else {
  17. Node* temp = head;
  18. while (temp->next) temp = temp->next;
  19. temp->next = newNode;
  20. }
  21. }
  22.  
  23. // Function to convert array to linked list
  24. Node* arrayToLinkedList(int arr[], int size) {
  25. Node* head = nullptr;
  26. for (int i = 0; i < size; ++i) {
  27. insertAtEnd(head, arr[i]);
  28. }
  29. return head;
  30. }
  31.  
  32. // Function to print the linked list
  33. void printList(Node* head) {
  34. while (head) {
  35. cout << head->data << " -> ";
  36. head = head->next;
  37. }
  38. cout << "NULL" << endl;
  39. }
  40.  
  41. // Main function
  42. int main() {
  43. int arr[] = {10, 20, 30, 40, 50};
  44. int size = sizeof(arr) / sizeof(arr[0]);
  45.  
  46. Node* head = arrayToLinkedList(arr, size);
  47. printList(head);
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
10 -> 20 -> 30 -> 40 -> 50 -> NULL