c program for linked list

#include<stdio.h>
#include<stdlib.h> //for malloc.h for allocating memory dynamically
struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
struct node *create_ll(struct node *);
struct node *display(struct node *);

main()
{
int option;
do{
printf("\n\n******MAIN MENU******");
printf("\n1.create linked list");
printf("\n2.Display the linked list");
printf("\n3..Enter your option\n\n");
scanf("%d",&option);
switch(option)
{
case 1:
start=create_ll(start);
printf("\n LINKED LIST CREATED");
break;
case 2:
start=display(start);
break;
}
}while(option!=3);
return 0;
}
struct node *create_ll(struct node *start)
{
struct node *new_node; // we always declare pointer in strructure using keyword struct folwed by the function name
int num;
printf("\n Enter -1 to end");
printf("\n Enter the data:");
scanf("%d",&num);
while(num!=-1)
{
new_node=(struct node*)malloc(sizeof(struct node *)); /*for memory allocation using ptr = (cast-type*)malloc(byte-size); here we are using new_node as it is pointer declared as  struct node *new_node; */
new_node->data=num;
if(start==NULL)
{
new_node->next = NULL;
start =new_node;
}
else
{
new_node->next =start;
start=new_node;
}
printf("\n Enter the data:");
scanf("%d",&num);
}
return start;
}
struct node *display(struct node *strat)
{
struct node *ptr;
ptr =start;
printf("\n");
while(ptr!=NULL)
{
printf("\t %d",ptr->data);
ptr=ptr->next;
}
return start;
}

Comments

Popular posts from this blog

cpanel exam CPSP Answers

How to install zimbra collaboration suite 8.8.11 on CentOS 7

awstats installation