Write a c program implementing linked lists

Below program illustrates operations as insert, delete, search & display with menu choice operations in linked list.

 #include <stdio.h>  
#include <stdlib.h>
struct NODE
{
int number;
struct NODE *next;
};
int search(struct NODE *list, int num);
void insert(struct NODE *list, int num);
void display(struct NODE *list);
void delete(struct NODE *list, int num);
int main(void)
{
int num = 0;
int input = 1;
int retval = 0;
struct NODE *list;
list = (struct NODE *)malloc(sizeof(struct NODE));
list->number = 0;
list->next = NULL;
while(input != 0)
{
printf("n**select number**n0) Quitn1) Insertn2) Deleten3) Searchn4) Displayn");
scanf("%d", &input);
switch(input)
{
case 0:
default:
printf("Goodbye ...n");
input = 0;
break;
case 1:
printf("Your choice: `Insertion'n");
printf("Enter the value which should be inserted: ");
scanf("%d", &num);
insert(list, num);
break;
case 2:
printf("Your choice: `Deletion'n");
printf("Enter the value which should be deleted: ");
scanf("%d", &num);
delete(list, num);
break;
case 3:
printf("Your choice: `Search'n");
printf("Enter the value you want to find: ");
scanf("%d", &num);
if((retval = search(list, num)) == -1)
printf("Value `%d' not foundn", num);
else
printf("Value `%d' located at position `%d'n", num, retval);
break;
case 4:
printf("You choice: `Display'n");
display(list);
break;
} /* switch */
} /* while */
free(list);
return(0);
}
void display(struct NODE *list)
{
while(list->next != NULL)
{
printf("%d ", list->number);
list = list->next;
}
printf("%d", list->number);
}
void insert(struct NODE *list, int num)
{
while(list->next != NULL)
list = list->next;
list->next = (struct NODE *)malloc(sizeof(struct NODE));
list->next->number = num;
list->next->next = NULL;
}
void delete(struct NODE *list, int num)
{
struct NODE *temp;
temp = (struct NODE *)malloc(sizeof(struct NODE));
if(list->number == num)
{
/* remove the node */
temp = list->next;
free(list);
list = temp;
}
else
{
while(list->next->number != num)
list = list->next;
temp = list->next->next;
free(list->next);
list->next = temp;
}
}
int search(struct NODE *list, int num)
{
int retval = -1;
int i = 1;
while(list->next != NULL)
{
if(list->next->number == num)
return i;
else
i++;
list = list->next;
}
return retval;
}

This entry was posted in c. Bookmark the permalink.