C PROGRAM - SINGLY LINKED LIST

 

 

//To count the total nodes of the linked list and to insert an element at the end of the linked list

 

#include<stdlib.h>

#include<stdio.h>

#include<conio.h>

 

struct node

{

            int data;

            struct node *next;

}*start = NULL;

 

void insert_end()

{

            struct node *temp,*ptr;

            temp = malloc(sizeof(struct node));

 

            scanf("%d",&temp->data );

            temp->next =NULL;

            if(start==NULL)

                        start=temp;

            else 

            {

                        ptr=start;

                        while(ptr->next !=NULL) 

                                    ptr=ptr->next ;

                        ptr->next =temp;

            }

}

 

void display()

{

            int count=0;

            struct node *ptr;

                        ptr=start;

                        printf("\n\nElements in the Linked List are: ");

                        while(ptr!=NULL)

                        {

                                    printf("%d\t",ptr->data );

                                    count++;

                                    ptr=ptr->next ;

                        }

            printf("\n\nTotal number of nodes in the Linked list is %d", count);

            }

 

 

void main()

{

            char ch;

            clrscr();

 

            do

            {

                        printf("\nEnter the data value for the node: ");

                        insert_end();

                        printf("Continue to add element at end of list(y/n):");

                        ch=getch();

 

            } while (ch=='y’);

 

            display();

            getch();

}

 

 

OUTPUT:

 

Enter the data value for the node: 5

Continue to add element at end of list(y/n): y

Enter the data value for the node: 4

Continue to add element at end of list(y/n): y

Enter the data value for the node: 6

Continue to add element at end of list(y/n): n

 

Elements in the Linked List are: 5      4       6

 

Total number of nodes in the Linked list is 3

Comments

Popular posts from this blog

Backtracking - N-Queens Problem, Sum of Subsets, Graph Colouring, Hamiltonian Cycle

Divide and Conquer Technique - Binary Search, Quick Sort, Merge Sort

GRAPH THEORY