Simplifying a simple linked list with a search function.
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node link;
link *searchList(int value, link *head);
int main()
{
struct node *first, *current, *temp;
first = calloc(1, sizeof(struct node));
current = first;
int i = 0;
for (i = 0; i < 9; i++)
{
temp = calloc(1, sizeof(struct node));
temp->data = i;
current->next = temp;
current = current->next;
}
current = first->next;
printf("Printing node values...\n");
while (current)
{
printf("%d\n", current->data);
current = current->next;
}
int search = 0;
printf("-----------------\n");
printf("Please enter a value to search for: ");
scanf("%d", &search);
current = first->next;
printf("[%d %d]\n", search, searchList(search, first)->data);
printf("(if the function returns [(value that's not 0) 0], it means that the term you searched for was not found)\n");
current = first->next;
while (current)
{
free(current);
current = current->next;
}
free(first);
return 0;
}
link *searchList(int value, link *head)
{
struct node *temp;
temp = head;
while(head)
{
if(value == head->data)
{
return head;
}
head = head->next;
}
head = temp;
return head;
}
It fills the singly-linked list with 0 through 9 and calls a function to prompt the user to search for a number. I don't see any glaring errors, I was just wondering what could be done to simplify it or if there's anything I missed.