I'm currently learning C/C++ and I saw this question on Reddit on how to create a linked from an array and decided that would make a good exercise for learning the absolute basics of C, so without looking at the answers I wrote this.
Anyways, preamble aside, here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct Node Node;
typedef struct Node {
int data;
Node *next;
} Node;
Node *array_to_list(int32_t array[], int32_t length) {
if (length <= 0) {
return NULL;
}
Node* tail = NULL;
for (int32_t i = length - 1; i >= 0; i--) {
Node* current = (Node*) malloc(sizeof(Node));
current->data = array[i];
current->next = tail;
tail = current;
}
return tail;
}
void free_list(Node *head) {
while (head != NULL) {
Node *next = head->next;
free(head);
head = next;
}
}
int main() {
int array[] = { 1, 2, 3, 4, 5 };
Node *list = array_to_list(array, 5);
Node *current = list;
while (current != NULL) {
printf("%d\n", current->data);
current = current->next;
}
free_list(list);
return 0;
}
As of now this is all inside main.c
and I didn't implement any other methods a linked list would normally have, I'm just trying to see if I'm doing things right