Hello friends!!!!!
Linear Search in Singly Linked List
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *link;
} Node;
Node* create_Node(int val) {
Node *new_node;
new_node = (Node *)malloc(sizeof(Node));
if(new_node == NULL) {
printf("Allocation failed");
exit(1);
}
new_node->data = val;
new_node->link = NULL;
return new_node;
}
void insert_at_begin(Node **q, int val) {
Node *new_node = create_Node(val);
new_node->link = *q;
*q = new_node;
}
void insert_at_end(Node **q, int val) {
Node *new_node = create_Node(val);
if (*q == NULL) {
*q = new_node;
} else {
Node *temp = q;
while (temp->link != NULL) {
temp = temp->link;
}
temp->link = new_node;
}
}
int del(Node **q, int value) {
Node *temp = q, *prev = NULL;
if (*q == NULL) {
return -1;
}
if (temp != NULL && temp->data == value) {
*q = temp->link;
free(temp);
return value;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->link;
}
if (temp == NULL) {
return -1;
}
prev->link = temp->link;
free(temp);
return value;
}
void display(Node *q) {
if (q == NULL) {
printf("List is empty\n");
return;
}
Node *temp = q;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->link;
}
printf("\n");
}
int search(Node **head, int value){
Node *temp;
temp = *head;
while(temp != NULL){
if(temp->data == value){
break;
}
temp = temp -> link;
}
if(temp!=NULL){
printf("Element exist\n");
}
else{
printf("Not exist\n");
}
}
int main() {
int i;
Node *head = NULL;
insert_at_begin(&head, 20);
insert_at_begin(&head, 30);
insert_at_end(&head, 40);
insert_at_end(&head, 50);
insert_at_end(&head, 10);
search(&head, 80);
display(head);
}