It only prints the first element
After that it shows the same output everytime.
Any help will be appreciated.
Code:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *start;
void insert_n(int val,int x)
{
int c=0;
int i;
struct node *preptr;
struct node *ptr=(node *)malloc(sizeof(struct node));
if((start==NULL)&&(x>1))
{
printf("\nEmpty list.Cannot insert at given position.");
}
else if((start==NULL)&&(x==1))
{
ptr->data=val;
ptr->next=start;
start=ptr;
}
else if((start!=NULL)&&(c<x))
{
for(i=0;i<x-2;i++)
{
preptr=preptr->next;
}
ptr->data=val;
ptr->next=preptr->next;
preptr->next=ptr;
c++;
}
}
void print()
{
struct node *temp;
temp=start;
while(temp->next!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
printf("%d",temp->data);
}
void main()
{
int i,n,x,val;
clrscr();
start=NULL;
printf("\nhow many elements: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter new alement: ");
scanf("%d",&val);
printf("\nEnter position: ");
scanf("%d",&x);
insert_n(val,x);
print();
}
getch();
}