I was going through implementation of single linked list, and I came across whenever I try to add a node at beginning with a function call addatbegin()
my program ends abruptly with return value 3221225477
.
I am attaching whole code here ,all functions working fine am just problem with addatbegin()
function .kindly help me out in finding the error.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* link;
};
struct node* root;
int len;
void append();
void addatbegin();
void addafter();
int length();
void Delete();
void display();
int main()
{
int ch;
while(1)
{
printf("Single Linked List Operations :\n");
printf("1.Append\n");
printf("2.Addatbegin\n");
printf("3.Addafter\n");
printf("4.Length\n");
printf("5.Delete\n");
printf("6.Display\n");
printf("7.Quit\n");
printf("Enter your choice :");
scanf("%d",&ch);
switch(ch)
{
case 1 : append();
printf("\n\n");
break;
case 2 : addatbegin();
break;
case 3 : addafter();
break;
case 4 : len=length();
printf("Length is :%d\n\n",len);
break;
case 5 : Delete();
break;
case 6 : display();
break;
case 7 : exit(0);
default : printf("Invalid Input\n\n");
}
}
}
void append()
{
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter node data :");
scanf("%d",&temp->data);
temp->link=NULL;
if(root==NULL)
root=temp;
else{
struct node *p;
p=root;
while(p->link!=NULL)
{
p=p->link;
}
p->link=temp;
}
}
void display()
{
struct node* temp;
temp=root;
if(temp==NULL)
printf("List is empty\n\n");
else{
while(temp!=NULL)
{
printf("%d-->",temp->data);
temp=temp->link;
}
printf("\n\n");
}
}
int length()
{
struct node* temp;
int count=0;
temp=root;
while(temp!=NULL)
{
count++;
temp=temp->link;
}
return count;
}
void addatbegin()
{
struct node* temp;
printf("Enter node data :");
scanf("%d",&temp->data);
if(root==NULL)
root=temp;
else
{
temp->link=root;
root=temp;
}
printf("Node inserted sucessfully\n\n");
}
void Delete()
{
struct node* temp;
int loc;
printf("Enter the location : ");
scanf("%d",&loc);
if(loc>length())
{
printf("Invalid Location\n\n");
}else if(loc==1)
{
temp=root;
root=temp->link;
temp->link=NULL;
free(temp);
}else{
struct node *p;
temp=root;
int i=1;;
while(i<loc-3)
{
temp=temp->link;
i++;
}
p=temp->link;
temp->link=p->link;
p->link=NULL;
free(p);
printf("Node deleted sucessfully\n\n");
}
}
void addafter()
{
struct node* temp;
int loc;
printf("Enter the location : ");
scanf("%d",&loc);
if(loc>length())
printf("Invalid location\nCurrently list is having %d nodes\n",length());
else{
int i=1;
struct node* p=root;
while(i<loc)
{
p=p->link;
i++;
}
temp=(struct node*)malloc(sizeof(struct node*));
printf("Enter node data : ");
scanf("%d",&temp->data);
temp->link=NULL;
temp->link=p->link;
p->link=temp;
printf("Node inserted successfully\n\n");
}
}