Tuesday, 13 March 2018

Insertion at first in Singly 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 addfirst(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);
}
addfirst(&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 addfirst(struct node **q)
{
struct node *temp, *r;
temp=*q;
r=(struct node *)malloc(sizeof(struct node));
printf("\n\nEnter value for 1st element:- ");
scanf("%d",&r->data);
r->ref=temp;
*q=r;

}



No comments:

Post a Comment