Singly Linked List: Create a list
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
typedef struct node * NODE;
NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct node));
if(x == NULL)
{
printf("\nInsufficient memory");
exit(0);
}
x->link = NULL;
return x;
}
NODE insert_at_end(NODE first)
{
int val;
NODE temp, cur;
temp = getnode();
printf("\nEnter the value: ");
scanf("%d", &val);
temp->data = val;
/*Case 1: List is empty*/
if(first == NULL)
return temp;
/*Case 2: List has nodes: Traverse till the end of the list*/
cur = first;
while(cur->link!=NULL)
{
cur = cur->link;
}
/*Set the link field of last node to point to temp node*/
cur->link = temp;
return first;
}
NODE create_list(NODE first)
{
int i, n;
printf("\nCreating the list: ");
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
/*Number of nodes 0*/
if(n==0)
return first;
printf("\nEnter the VALUES for nodes: ");
for(i=1;i<=n;i++)
first= insert_at_end(first);
return first;
}
void display(NODE first)
{
NODE cur;
cur = first;
printf("\nContents are:");
if(cur == NULL)
printf("\nList is empty. Nothing to display.");
else
{
while(cur!=NULL)
{
printf("%d ", cur->data);
cur = cur->link;
}
}
}
void main()
{
int ch;
NODE first = NULL;
first = create_list(first);
display(first);
}
Output:
Creating the list:
Enter the number of nodes: 4
Enter the VALUES for nodes:
Enter the value: 11
Enter the value: 12
Enter the value: 13
Enter the value: 14
Contents are:11 12 13 14
No comments:
Post a Comment