Hi ,
I was just trying to understand linked list using this program but when compiled it does not give any error but on running the same it gives unhandled exception. The compiler i am using is the visual c++ 2009.
[insert]
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
void addatend(struct node **, int);
void addatbeg(struct node**, int);
void addatloc(struct node*, int , int);
void display(struct node *);
void count(struct node *);
int main(void){
struct node *p;
p = NULL;
//display (p);
count (p);
addatend(&p, 15);
addatend(&p, 12);
addatend(&p, 23);
display (p);
count (p);
addatbeg(&p, 54);
addatbeg(&p, 78);
addatbeg(&p, 35);
display (p);
count (p);
addatloc(p, 2, 32);
addatloc(p, 5, 36);
display (p);
count (p);
return 0;
}
void addatend (struct node **q, int num){
struct node *temp, *r;
if(*q = NULL){
temp = malloc(sizeof(struct node));
temp -> data = num;
temp -> link = NULL;
*q = temp;
}
else{
temp = *q;
while(temp -> link != NULL)
temp = temp ->link;
r = malloc(sizeof(struct node));
r ->data = num;
r ->link = NULL;
temp -> link = r;
}
}
void addatbeg(struct node **q, int num){
struct node *temp;
temp = malloc(sizeof(struct node));
temp ->data = num;
temp ->link = *q;
*q= temp;
}
void addatloc(struct node*q, int loc, int num){
struct node *temp, *r;
int i;
temp = q;
for(i = 0; i< loc ; i++){
temp = temp ->link;
}
r = malloc(sizeof(struct node));
r ->data = num;
r ->link = temp->link;
temp ->link = r;
}
void display (struct node *q){
int i = 0;
struct node *temp;
temp = q;
while (temp ->link != NULL){
printf("\nThe data at loc %d is %d", i , temp ->data);
i++;
}
}
void count (struct node *q){
struct node *temp;
int count = 0;
temp = q;
while (temp ->link != NULL){
++count;
}
printf("\n%dThe total no. of elements in linked list is ", count);
}