Sunday, 6 May 2012

Insert at a specific position in a Linked List in C


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


typedef struct nodetype
{
int info;
struct nodetype *link;
}node;


node *start = NULL;


int main()
{
void add(int);
void disp();
void insert(int,int);
void del();
int value,pos,total=0;
char choice;

while(1)
{
printf("\nDo you wish to insert an element in the Linked List (Y/N)?\n");
scanf("%c",&choice);
if(choice=='y'||choice=='Y')
{
printf("Enter the info part of the node\n");
scanf("%d",value);
add(value);
total++;
fflush(stdin);
}
else
{
break;
}
}
printf("\nThe Linked List is:\n\n");
disp();
printf("\nEnter the position of insertion <= %d\n",total+1);
scanf("%d",&pos);
if(pos<=0||pos>total+1)
{
printf("Wrong position inputted\n");
getch();
}
printf("Enter the info of the node to be inserted: ");
scanf("%d",&value);
insert(pos,value);
printf("\n\nThe list after the opeartion is:\n\n");
disp();
del();
getch();
return 0;
}


void add(int data)
{
node *newptr = NULL;
node *ptr;

newptr = (node*)malloc(sizeof(node));

newptr->info=data;
newptr->link=NULL;
if(start==NULL)
{
start=newptr;
}
else
{
ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=newptr;
}
}


void disp()
{
node *ptr;
printf("->");
while(ptr)
{
printf("%d->",ptr->info);
ptr=ptr->link;
}
printf("NULL\n");
}


void insert(int position,int data)
{
node *newptr = NULL;
node *ptr=start;
int steps=1;

newptr=(node*)malloc(sizeof(node));
newptr->info=data;

while(steps<position-1)
{
ptr=ptr->link;
steps++;
}
if(position==1)
{
newptr->link=start;
start=newptr;
}
else
{
newptr->link=ptr->link;
ptr->link=newptr;
}
}


void del()
{
node *ptr;
while(start!=NULL)
{
ptr=start;
start=start->link;
free(ptr);
}
}

No comments:

Post a Comment