Tuesday, 13 March 2018

Insertion at last in Linked List

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>

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

void create(struct node **);
void display(struct node *);
void addlast(struct node **);

void main()
{
struct node *head=NULL;
int i,num;
clrscr();
printf("\nEnter no. of elements for your node:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
addlast(&head);
display(head);
getch();
}

void create(struct node **q)
{
struct node *temp, *r;
temp=*q;
if(*q==NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&temp->data);
temp->ref=NULL;
*q=temp;
}
else
{
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&r->data);
r->ref=NULL;
while(temp->ref!=NULL)
{
temp=temp->ref;
}
temp->ref=r;

}

}

void display(struct node *p)
{
while(p!=NULL)
{
printf("\nOUTPUT:- %d",p->data);
p=p->ref;
}
}

void addlast(struct node **q)
{
struct node *temp, *l;
temp=*q;
l=(struct node *)malloc(sizeof(struct node));
printf("\n\nEnter value for last element:- ");
scanf("%d",&l->data);
l->ref=NULL;
while(temp->ref!=NULL)
{
temp=temp->ref;
}
temp->ref=l;

}


No comments:

Post a Comment