# include <stdio.h>
# include <stdlib.h>
struct node //creating a structure called node
{
int data; //Linked list data(value)
struct node *link; // Linked list node(pointer)
};
struct node *insert(struct node *p , int num) //Function to insert a node in linked list
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node)); //Allocating memory for the new node.
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = num;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link != NULL) // Loop to traverse to the end of the list
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node)); //Allocating memory
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = num;
temp-> link = NULL;
}
return (p);
}
void printlist ( struct node *p )
{
printf("The data values of your list are\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p-> link;
}
}
No comments:
Post a Comment