0
826views
Write a C program to implement singly linked list that performs following function 1. Insert a node in the beginning 2. Delete a specified node 3. Search for a specific value 4. Displaying the list
1 Answer
0
36views


Program : -

//C program for implementation of Linked List
#include<stdio.h>
#include<stdlib.h>

struct node{
    int data;
    struct node *next;
};

struct node *head = NULL;
struct node *tail = NULL;

void insertAtHead(int data){
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = head;

    if (head == NULL){
       head = newNode;
       tail = newNode;
    }
    else{
        newNode->next = head;
        head = newNode;
    }
}

void insertAtTail(int data){
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = NULL;

    if (head==NULL){
        head = newNode;
        tail = newNode;
    }
    else {
        tail->next = newNode;
        tail = newNode;
    }
}

void search(int num){
    int count=0;
    struct node *ptr = head;
    if (head == NULL){
        printf("List is empty hence no element found");
        return;
    }
    while(ptr != NULL){
        if (ptr->data == num){
            count++;
        }
        ptr = ptr->next;
    }
    if (count == 1){
        printf("Element is found!\n");
    }
    else {
        printf("Element is not found!\n");
    }
}

void deletion(int num){
    int count=0;
    struct node *ptr = head;
    struct node *ptr2 = tail;
    struct node *preptr;
    if (head == NULL){
        printf("List is empty hence no element found");
        return;
    }
    if (ptr->data == num){
        head = head->next;
        return;
    }
    if (ptr2->data == num){
        while(ptr->next != NULL){
            preptr = ptr;
            ptr = ptr->next;
        }
        preptr->next = NULL;
        return;
    }
    while(ptr != tail){
        if (ptr->next->data == num){
            ptr->next = ptr->next->next;
            return;
        }
        ptr = ptr->next;
    }
}

void display(){
    struct node *current = head;
    if (head == NULL){
        printf("Linked list is empty!\n");
        return;
    }
    while(current != NULL){
        printf("%d->", current->data);
        current = current->next;
    }
    printf("NULL");
    printf("\n");
}

int main(){
    insertAtTail(7);
    display();
    insertAtHead(2);
    display();
    insertAtHead(1);
    display();
    insertAtTail(9);
    display();
    insertAtTail(45);
    display();
    return 0;
}
//Enjoy coding.....
Please log in to add an answer.