#ifndef LL_H
#define LL_H
// A single list node that stores an int as value
typedef struct Node {
int value;
struct Node* next;
} Node;
// Allocates a new node on the heap.
Node* makeNode(int value, Node* next);
// Builds a heap-allocated linked list with the values in the array.
Node* fromArray(int* array, int length);
// Frees all nodes in the linked list.
void freeList(Node* list);
// Prints the contents of the linked list.
void printList(Node* list);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
Node* makeNode(int value, Node* next);
Node* fromArray(int* array, int length) {
Node* front = NULL;
for (int i = length - 1; i >= 0; i--) {
front = makeNode(array[i], front);
}
return front;
}
void freeList(Node* list) {
while (list != NULL) {
Node* next = list->next;
free(list);
list = next;
}
}
void printList(Node* list) {
printf("[");
while (list != NULL) {
printf(" %d", list->value);
list = list->next;
}
printf(" ]\n");
}
Node* makeNode(int value, Node* next) {
Node* n = (Node*) malloc(sizeof(Node));
n->value = value;
n->next = next;
return n;
}
#include <stdlib.h>
#include "linkedlist.h"
/*
Creates two integer linked list from the given array,
and print out the values.
*/
int main(int argc, char **argv) {
int arr1[3] = {1, 2, 3};
Node* list1 = fromArray(arr1, 3);
printList(list1);
int arr2[4] = {4, 3, 2, 1};
Node* list2 = fromArray(arr2, 4);
printList(list2);
freeList(list1);
freeList(list2);
return EXIT_SUCCESS;
}