HOME

Tuesday, February 7, 2017

//program to add node in a link list
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
};
struct node *first=NULL;
struct node *last=NULL;
void insert(int);
void display(void);
void main()
{
int v,ch;
while(1)
{
printf("1. Insert Data\n");
printf("2. Display List \n");
printf("3. Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
    printf("Enter Value to insert\n");
    scanf("%d",&v);
    insert(v);
    break;
case 2:
    printf("The list is\n");
    display();
    break;
case 3:
    exit(1);
    break;
default:
    printf("Wrong input");
    break;

}
}
}
void insert(int v)
{
    struct node *ptr;
    ptr=(struct node*)malloc(sizeof(struct node));
    ptr->data=v;
    if(first==NULL)
    {
        first=last=ptr;
        ptr->next=NULL;
    }
    else
    {
        last->next=ptr;
        ptr->next=NULL;
        last=ptr;
    }
}
void display()
{
struct node *ptr;
if(first==NULL)
{
    printf("No Record Found\n");
}
else if(first==last)
    {
        printf("%d\n",first->data);
    }
    else
    {
        for(ptr=first;ptr!=last;ptr=ptr->next)
        {
            printf("%d\n",ptr->data);
        }
        printf("%d\n",last->data);
    }
}

No comments:

Post a Comment