#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int number;
struct node* next;
};
struct node* first = NULL;
struct node* add_to_list(struct node* list, int n);
struct node* insert_nth(struct node* list, int n, int new_number);
int length(struct node* list);
struct node* search_list(struct node* list, int n);
struct node* find_nth(struct node* list, int n);
struct node* delete_from_list(struct node* list, int n);
int main(void)
{
first = add_to_list(first, 10);
first = add_to_list(first, 20);
first = add_to_list(first, 40);
insert_nth(first, 2, 30);
printf("The length of the liked list:%d", length(first));
search_list(first, 30);
find_nth(first, 3);
delete_from_list(first, 20);
return 0;
}
struct node* add_to_list(struct node* list, int n)
{
struct node* new_node = malloc(sizeof(struct node));
if (new_node==NULL)
{
printf("Error:malloc failed in add_to_list\n");
exit(EXIT_FAILURE);
}
new_node->number = n;
new_node->next = list;
return new_node;
}
int length(struct node* list)
{
int counter;
struct node* p = list;
for (counter=0; p != NULL; counter++)
{
p = p->next;
}
return counter;
}
struct node* search_list(struct node* list, int n)
{
struct node* p;
for (p=list; p != NULL; p=p->next)
{
if (p->number==n)
{
return p;
}
}
return NULL;
}
struct node* find_nth(struct node* list, int n)
{
struct node* p = list;
int i;
for (i = 1; p != NULL && i < n;i++)
{
p = p->next;
}
if (i==n && p != NULL)
{
return p;
}
else
{
return NULL;
}
}
struct node* delete_from_list(struct node* list, int n)
{
struct node* current, * previous;
for (previous = NULL, current = list;
current != NULL && current != n;
previous = current, current = current->next)
;
if (current==NULL)
{
return NULL;
}
if (previous==NULL)
{
list = list->next;
}
else
{
previous->next = current->next;
}
free(current);
return NULL;
}
struct node* insert_nth(struct node* list, int n, int new_number)
{
struct node* new_node, * previous, * current;
int i;
new_node = malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("Error:malloc failed in add_to_list\n");
exit(EXIT_FAILURE);
}
if (n == 1)
{
new_node->number = new_number;
new_node->next = list;
return new_node;
}
for (previous = NULL, current = list, i = 1;
current != NULL && i < n;
previous = current, current = current->next, i++)
;
if (current == NULL)
{
printf("Error:n was not found\n");
free(previous);
free(current);
return NULL;
}
else
{
new_node->number = new_number;
previous->next = new_node;
new_node->next = current;
return new_node;
}
}