I made a simple linked list in C with the following functionalities: Create(creates the list); Find(searches for an element in the list); Insert(inserts a value at the beginning of the list); Destroy(destroys the entire list). It only uses integers (for simplicity), and I want to know for possible errors and how to improve it in general.
The node structure:
typedef struct sllist
{
int val;
struct sllist* next;
}
sllnode;
The functions:
#include <stdio.h>
#include <stdlib.h>
#include "node.c"
/*
*Creates the linked list with a single value
*/
sllnode *create(int value)
{
sllnode *node;
node = (sllnode *) malloc(sizeof(sllnode));
if (node == NULL)
{
puts("Memory error");
return NULL;
}
node->val = value;
node->next = NULL;
return node;
}
/*
*Searches for an element in the list.
*Returns 1 if its found or 0 if not
*/
int find(sllnode *head, int value)
{
sllnode *trav = head;
do
{
if (trav->val == value)
{
return 1;
}
else
{
trav = trav->next;
}
} while (trav != NULL);
return 0;
}
/*
*Inserts a value at the beginning of the list
*/
sllnode *insert(sllnode *head, int value)
{
sllnode *new_node = (sllnode *) malloc(sizeof(sllnode));
if (new_node == NULL)
{
puts("Memory error");
return NULL;
}
new_node->val = value;
new_node->next = head;
head = new_node;
return head;
}
/*
*Destroys (i.e frees) the whole list
*/
void *destroy(sllnode *head)
{
sllnode *temp = head;
while (temp != NULL)
{
free(temp);
temp = temp->next;
}
free(head);
}
int main(void)
{
return 0;
}