linked list 1- insertion at begining of the list

                                                                                    click here for insertion at end

c program to insert the elements at the beginning of the linked list and to print them from starting node to end node

Introduction: when you don't know the size of input data, prior to the compilation, using a large size array in the program is not efficient method. So take the advantage of linked list that it takes the memory at the execution time with the help of 'malloc' function according to the size of the input.

Program:

/*       c program to insert the elements at the beginning of the linked list         */
#include<stdlib.h>
#include<stdio.h>
int main()
{
             typedef struct node_type{  /* structure declaration for a node */
             int dat;
             struct node_type *next;
             }node;
             node *head;  /* pointer to the start node */
             node *temp;  /* temporary pointer to a node   */
             int n;          /* to read data from user */
             char ch;
             head=NULL;  /* initializing list to be empty */
             printf("enter data?\n");
             printf("say y(yes) or n(no): ");
             scanf("%c",&ch);
             fflush(stdin);
             while((ch=='y')||(ch=='Y'))
             {
                     scanf("%d",&n);                             /* read data*/
                     temp=(node *)(malloc(sizeof(node)));  /* heap memory */
                     temp->dat=n;        /* store data in 'data part' of the node */
                     temp->next=head;       /* to insert at beginning of the list */
                     head=temp;
                     fflush(stdin);
                     printf("say y(yes) or n(no): ");
                     scanf("%c",&ch);
             }
              temp=head;
              while((temp)!=NULL){      /*  while list is not empty  */
                       printf("%d  ",temp->dat);
                       temp=temp->next;
             }
             return 0;
}

Sample input:

enter data?
say y(yes) or n(no): y
5
say y(yes) or n(no): y
7
say y(yes) or n(no): y
8
say y(yes) or n(no): y
9
say y(yes) or n(no): n

Output:

9  8  7  5
                                                                           click here for insertion at end

 

No comments: