You are on page 1of 2

#include<stdlib.

h>
#include<string.h>
#include<stdio.h>

struct node
{
char Name[100];
int age;
struct node *nextptr;
}*head;
void createNodeList(int n);
void displayList();

int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int age,i,Name;
head = (struct node *)malloc(sizeof(struct node));

if(head == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for Student 1 \n: ");
printf("Enter the Name of the Student\n");
scanf("%c", &Name);
printf("Enter the Age of the Student\n\n");
scanf("%d", &age);
strcpy(head->Name, Name);
head->age = age;
head->nextptr = NULL; // links the address field to NULL
tmp = head;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for Student %d \n: ", i);
printf("Enter the Name of the Student\n");
scanf("%c", &Name);
printf("Enter the Age of the Student\n");
scanf(" %d", &age);
strcpy(head->Name, Name);
fnNode->age = age; // links the num field of fnNode with num
fnNode->nextptr = NULL; // links the address field of fnNode with NULL
tmp->nextptr = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->nextptr;
}
}
}
}
void displayList()
{
struct node *tmp;
if(head == NULL)
{
printf(" List is empty.");
}
else
{
tmp = head;
while(tmp != NULL)
{
printf(" Name of Student = %c Age of student=%d \n",tmp->Name, tmp->age); // prints the
data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}

You might also like