Delete, Search, Count A Node in Linked List
Delete, Search, Count A Node in Linked List
list
Delete a node
Delete a given node from the linked list.
Example:
Input
Enter node to delete :20
Output
10-> 30 NULL
Algorithm
node
free its memory.
1. Delete the Head node has the given key
struct Node
{
int data;
struct Node *next;
}*head=NULL;
int main() {
/* insert your code here */
int data,n,key;
void append(struct Node**,int);
void display(struct Node*);
void deleteNode(struct Node **,int);
}
void deleteNode(struct Node **head,int key)
{
struct Node *temp;
if((*head)->data ==key)
{
temp=*head;
*head=(*head)->next;
free(temp);
}
else
{
struct Node *current=*head;
while(current->next!=NULL)
{
if(current->next->data==key)
{
temp=current->next;
current->next=current->next->next;
free(temp);
break;
}
else
current=current->next;
}
}
Output
Enter the number of nodes:
4
10 20 30 40
The elements in the linked list are
10->20->30->40->NULL
Enter the value to delete :20
After deletion the nodes are
The elements in the linked list are
10->30->40->NULL
Count the number of nodes in the
linked list
int count ( struct Node * head )
{
int count=0;
struct Node *temp=head;
while(temp!=NULL)
{
count+=1;
temp=temp->next;
}
return count;
}
Search a node in the linked list
int search ( struct Node *head, int key )
{
struct Node *temp=head;
int flag=0;
while(temp!=NULL)
{
if(temp->data==key)
{
flag=1;
break;
}
else
flag=0;
temp=temp->next;
}
return flag;
}