C Program to illustrate the operations of singly linked list


March 11, 2022, Learn eTutorial
1326

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this C program, we have to illustrate the operations of a singly linked list.

What is a linked list?

A linked list is simply a set of dynamically allocated nodes arranged so that each node contains one value and one pointer. Which is called and head and the body. In other words, linked lists are the best example of a dynamic data structure that uses a pointer for its implementation.

Then we also have to know the representation of the linked list in a c language. A linked list is represented by a pointer to the first node of the linked list. In other words, the linked list is a sequence of data structures that are connected using links. Every link contains a connection with other nodes. It is the most used data structure after arrays. In the c programming language, linked lists can be implemented using structures and pointers.

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

In this c program, after Including the header files, we make variable declarations; also, we have to declare the structure and a linked list. Then we display the menu for the user to select which operations the user wants to do on the linked list. According to the choice call, the appropriate functions. which are

  • Insert
  • Print
  • Delete
  • Search
  • Display

The insert() function will be used for which accepts the parameters as the user inputs that are to be added to the linked list, insert a node in the linked list. The printnode() prints the node.The deleteNode() function delete the node.The search function will perform the search operation in the Linked list. The display() function will display the LinkedList.

ALGORITHM

STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare EMP as structure with members empno,empName[max],char designation[max], and a poniter * next of type EMP. 

STEP 3: Declare the pointer *linklist of type EMP, choice as to character,eno as an integer.

STEP 4: Set linkList=NULL.

STEP 5: Display Welcome to a demonstration of the singly linked list.

STEP 6: Call the function menu().

STEP 7: By using a do-while loop, check the value of choice

STEP 8: If the choice is 1, then read the employe number, employe name, employe designation into the variable eno,name,desig, and do step 9.

STEP 9: Call the function insert() to insert the details into the LinkedList.

STEP 10: If the choice is 2, then read the employee number, which is deleted into the variable eno, and call it deleteNode()

STEP 11: If the choice is 3, check if linklist=NULL then display the empty list.Else call the function display(linkList).

STEP 12: If the choice is 4, then read the employee number, which is to be searched into the variable eno and call the function search().

STEP 13: If the choice is 5, then Exit.

Function struct EMP* insert(struct EMP *front, int id, char name[], char desg[])

STEP 1: Declare  the pointer *newnode of type EMP 

STEP 2: Assign newnode=(struct EMP*) malloc(sizeof(struct EMP)).

STEP 3: If newnode is null then exit else set newnode->empnn=id,copy name to newnode->empName,desg to newnode->designation ,and set newnode->next=front.

STEP 4: Return front.

Function printNode(struct EMP *p)

STEP 1: Display Employee Details using printf function.

STEP 2: Display Emp No,Name,Designation as p->empno,p->empName,p->designation.

Function struct EMP* deleteNode(struct EMP *front, int id)

STEP 1: Declare  the pointer *ptr,*bptr of type EMP 

STEP 2: Check if front->empno=id then set ptr=front.

STEP 3: Display Node deleted.

STEP 4: call the function printNode(front).

STEP 5: set fr to next and free(ptr).

STEP 6: Return front.

STEP 7: Set ptr=front->next,bptr=front.

STEP 8: By using a for loop with the condition ptr!=null do step 9.

STEP 9: Check if ptr->empno=id then display node deleted.Else do step 16.

STEP 10: call the function printNode(ptr).

STEP 11: set bptr->next=ptr->next.

STEP 12: Call the function free(ptr).

STEP 13: Return front.

STEP 14: call the function printNode(ptr).

STEP 15:s et bptr->next=ptr->next and repeat step 8.

STEP 16: Display employee number not found.

STEP 17: Return front.

Function void search(struct EMP *front, int key)

STEP 1: Declare  the pointer *ptr of type EMP 

STEP 2: Set ptr=front.

STEP 3: Using a for loop with the condition ptr!=null do step 4.Else do step 6.

STEP 4: Check if ptr->empno=key then display key found.

STEP 5: call the function printNode(ptr) and return.

STEP 6: Display employee number not found.

Function void display(struct EMP *front)  

STEP 1: Declare  the pointer *ptr of type EMP 

STEP 2: Set ptr=front.

STEP 3: Using a for loop with the condition ptr!=null do step 4.Else do step 6.

STEP 4: Call the function printNode(ptr).

STEP 5: Repeat step 3.

Function void menu()  

STEP 1: Display the menu for the user as 1 for insert a node,2 for delete a node,3 for display the list,4 to search, and 5 for the exit.

Function char option()

STEP 1: Declare the variable choice as type character.

STEP 2: Display Enter your choice.

STEP 3: Call the function choice=getche() .

STEP 4: Return choice.

C Source Code

                                          #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30
 
struct emp_data
{
    int  empno;
    char empName[MAX];
    char designation[MAX];
    struct emp_data *next;
};
 

/*  Function to insert a node at the front of the linked list.        */

struct emp_data *insert(struct emp_data *front, int id, char name[],
char desg[])
{
    struct emp_data *newnode;
 
    newnode = (struct emp_data*)malloc(sizeof(struct emp_data));
 
    if (newnode == NULL)
    {
        printf("\n Allocation failed \n");
        exit(2);
    }
    newnode->empno = id;
    strcpy(newnode->empName, name);
    strcpy(newnode->designation, desg);
    newnode->next = front;     fr
    return(front);
}
/*  End of insert() */
 
/*  Function to display a node in a linked list */
void printNode(struct emp_data *p)
{
    printf("\n Employee Details...\n");
    printf("\n Emp No       : %d", p->empno);
    printf("\n Name           : %s", p->empName);
    printf("\n Designation    : %s\n", p->designation);
    printf("-------------------------------------\n");
}
/*  End of printNode() */
/*  Function to deleteNode a node based on employee number */

struct emp_data* deleteNode(struct emp_data *front, int id)
{
    struct emp_data *ptr;
    struct emp_data *bptr;
 
    if (front->empno == id)
    {
        ptr = front;
        printf("\n Node deleted:");
        printNode(front);         fr>next;
        free(ptr);
        return(front);
    }
    for (ptr = front->next, bptr = front; ptr != NULL; ptr = ptr->next,
bptr = bptr->next)
    {
        if (ptr->empno == id)
        {
            printf("\n Node deleted:");
            printNode(ptr);
            bptr->next = ptr->next;
            free(ptr);
            return(front);
        }
    }
    printf("\n Employee Number %d not found ", id);
    return(front);
}
/*  End of deleteNode() */
/*  Function to search the nodes in a linear fashion based emp ID */

void search(struct emp_data *front, int key)
{
    struct emp_data *ptr;
 
    for (ptr = front; ptr != NULL; ptr = ptr -> next)
    {
        if (ptr->empno == key)
        {
            printf("\n Key found:");
            printNode(ptr);
            return;
        }
    }
    printf("\n Employee Number %d not found ", key);
}
/*  End of search() */
 
/*  Function to display the linked list */
void display(struct emp_data  *front)
{
    struct emp_data *ptr;
 
    for (ptr = front; ptr != NULL; ptr = ptr->next)
    {
        printNode(ptr);
    }
}
/*  End of display() */
 
/*  Function to display the menu of operations on a linked list */
void menu()
{
    printf("---------------------------------------------\n");
    printf("Press 1 to INSERT a node into the list       \n");
    printf("Press 2 to DELETE a node from the list       \n");
    printf("Press 3 to DISPLAY the list                 \n");
    printf("Press 4 to SEARCH the list                   \n");
    printf("Press 5 to EXIT                              \n");
    printf("---------------------------------------------\n");
}
/*  End of menu() */
 
/*  Function to select the option */
char option()
{
    char choice;
  
    printf("\n\n>> Enter your choice: ");

   
    switch(choice=getchar())
    {
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':   return(choice);
        default :   printf("\n Invalid choice.");
    }
    return choice;
}
/*  End of option() */
 
/*  The main() program begins */
void main()
{
    struct emp_data *linkList;
    char name[21], desig[51];
    char choice;
    int eno;
 
    linkList = NULL;
    printf("\n Welcome to demonstration of singly linked list \n");
    menu();
    do
    {
        /*  choose oeration to be performed */
        choice = option();
        switch(choice)
        {
        case '1':
            printf("\n Enter the Employee Number      : ");
            scanf("%d", & eno);
            printf("Enter the Employee name        : ");
            scanf("%s", & name);
            //gets(name);
            printf("Enter the Employee Designation : ");
            scanf("%s", & desig);
           // gets(desig);
            linkList = insert(linkList, eno, name, desig);
            break;
        case '2':
            printf("\n\n Enter the employee number to be deleted: ");
            scanf("%d", &eno;);
            linkList = deleteNode(linkList, eno);
            break;
        case '3':
            if (linkList == NULL)
            {
                printf("\n List empty.");
                break;
            }
            display(linkList);
            break;
        case '4':
            printf("\n\n Enter the employee number to be searched: ");
            scanf("%d", &eno;);
            search(linkList, eno);
            break;
        case '5': break;
        }
    } while (choice != '5');
}

                                      

OUTPUT

Welcome to a demonstration of a singly linked list
---------------------------------------------
Press 1 to INSERT a node into the list

Press 2 to DELETE a node from the list

Press 3 to DISPLAY the list

Press 4 to SEARCH the list

Press 5 to EXIT
---------------------------------------------


>> Enter your choice: 1
Enter the Employee Number: 1234
Enter the Employee name: Keerthi
Enter the Employee Designation: Engineer


>> Enter your choice: 1
Enter the Employee Number: 2345
Enter the Employee name: Srinivasan
Enter the Employee Designation: Specialist


>> Enter your choice: 1
Enter the Employee Number: 4567
Enter the Employee name: Annapurna
Enter the Employee Designation: Project Manager



>> Enter your choice: 3
Employee Details...
Emp No: 4567
Name: Annapoorna
Designation: Project Manager
-------------------------------------

Employee Details...

Emp No    : 2345
Name        : Srinivasan
Designation : Specilist
-------------------------------------

Employee Details...
Emp No: 1234
Name: Keerthi
Designation: Engineer
-------------------------------------


>> Enter your choice: 2
Enter the employee number to be deleted: 2345
Node deleted:

Employee Details...
Emp No: 2345
Name: Srinivasan
Designation: Specialist
-------------------------------------


>> Enter your choice: 3
Employee Details...
Emp No: 4567
Name: Annapurna
Designation: Project Manager
-------------------------------------

Employee Details...
Emp No: 1234
Name: Keerthi
Designation: Engineer
-------------------------------------


>> Enter your choice: 4
Enter the employee number to be searched: 2345
Employee Number 2345 not found
>> Enter your choice: 5