I'm not very comfortable with pointers in C and tried a piece of code to search a value in the linked list. Also, I made functions to insert at end(newNode_end), insert at the beginning(newNode_begin) and traverse.
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}
void newNode_end(node **head,int data)
{
node* node_ptr, *temp;
node_ptr = (node* )malloc(sizeof(node));
node_ptr->data = data;
if((*head)==NULL)
{
(*head) = node_ptr;
node_ptr->next = NULL;
}
else
{
temp = (*head);
while(temp->next!=NULL)
temp = temp->next;
temp->next = node_ptr;
node_ptr->next = NULL;
}
}
void newNode_begin(node **head,int data)
{
node* node_ptr, *temp;
node_ptr = (node* )malloc(sizeof(node));
node_ptr->data = data;
if((*head)==NULL)
{
(*head) = node_ptr;
node_ptr->next = NULL;
}
else
{
node_ptr->next = (*head);
(*head) = node_ptr;
}
}
void traverse(node *head)
{
node* temp;
if(head==NULL)
{
printf("The list is empty\n");
}
else
{
temp = head;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp = temp->next;
}
}
}
int search_value(node **head,int value)
{
node* temp;
if((*head)==NULL)
{
printf("The list is empty\n");
}
else
{
temp = (*head);
while(temp!=NULL)
{
if(temp->data==value)
{
printf("FOUND\n");
return 0;
}
}
printf("NOT FOUND\n");
return 0;
}
}
int main()
{
node *head = NULL;
int node_data,user_resp,value;
while(1)
{
printf("----------MENU------------\n");
printf("Press 1: ADD NODE IN THE BEGINNING\n");
printf("Press 2: ADD NODE AT THE END\n");
printf("Press 3: TRAVERSE THE LINKED LIST\n");
printf("Press 4: SEARCH A VALUE\n");
printf("Press 5: EXIT\n");
scanf("%d",&user_resp);
switch(user_resp)
{
case 1:
printf("Enter data for node\n");
scanf("%d",&node_data);
newNode_begin(&head,node_data);
break;
case 2:
printf("Enter data for node\n");
scanf("%d",&node_data);
newNode_end(&head,node_data);
break;
case 3:
traverse(head);
break;
case 4:
printf("Enter value to be searched\n");
scanf("%d",&value);
search_value(&head,value);
case 5:
exit(0);
break;
}
}
return 0;
}
The insertion and traversal functions of the code works well but the search_value function sometimes crashes. Any guidance on the same would be highly appreciated.
Thanks in advance.
Think about the search function:
int search_value(node **head,int value)
{
node* temp;
if((*head)==NULL)
{
printf("The list is empty\n");
}
else
{
temp = (*head);
while(temp!=NULL)
{
if(temp->data==value)
{
printf("FOUND\n");
return 0;
}
}
printf("NOT FOUND\n");
return 0;
}
}
In your while loop, you check if temp != NULL
and initialize temp to head
. It seems like you want to actually traverse the list, and when value
is found, you want to return. However, you never move to the next node.
You simply check the value of temp->data
, but unless the first node's data member equals value
, the while loop is infinite.
In order to actually traverse the loop, it would be best to do something like:
temp = temp->next;