Linked list creation in C

Aim: Create a singly linked list of n nodes and display its elements using C.

#include <stdio.h>
#include <malloc.h>

struct node
{
‎   int value;
‎   struct node *next;
};
‎
typedef struct node snode;
snode *newnode, *ptr;
snode *first = NULL, *last = NULL;

snode* create_node(int);
void insert_node(int);
void display();
‎
int main()
{
‎   int ch=0,n;
‎
‎   while (ch!=3)
‎   {   
‎       printf("\n---Linked List Operations---");
‎       printf("\n1.Create List \n2.Display List \n3.Exit\n");
‎       printf("\nEnter your choice : ");
‎       scanf("%d", &ch);
‎       switch (ch)
‎       {
‎       case 1:
‎           printf("\nEnter the number of elements : ");
‎           scanf("%d",&n);
‎           insert_node(n);
‎           break;
‎       case 2: 
‎           printf("\nElements in the list are : ");
‎           display();
‎           break;
‎       case 3:
‎           printf("Exiting...");
‎           break;
‎       default: 
‎           printf("\nInvalid Choice\n");
‎           break;
‎       }
‎   }
‎   return 0;
}

snode* create_node(int val)
{
‎   newnode = (snode *)malloc(sizeof(snode));
‎       newnode->value = val;
‎       newnode->next = NULL;
‎       return newnode;
}

void insert_node(int n)
{
‎   first = NULL,last=NULL;
‎   int val,i;
‎   for(i=0;i<n;i++)
‎   {
‎       printf("\nEnter the value for the Node %d : ",i+1);
‎       scanf("%d", &val);
‎       newnode = create_node(val);
‎       if (first == last && last == NULL)
‎       {
‎           first = last = newnode;
‎           first->next = NULL;
‎           last->next = NULL;
‎       }
‎       else
‎       {
‎           last->next = newnode;
‎           last = newnode;
‎           last->next = NULL;
‎       }
‎   }
‎   printf("\nLinked list created\n");
}    

void display()
{
‎   if (first == NULL)
‎   {
‎       printf("\nNo nodes in the list to display\n");
‎   }
‎   else
‎   {
‎       for (ptr = first;ptr != NULL;ptr = ptr->next)
‎       {    
‎           printf("  %d  ", ptr->value);
‎       }
‎   }
}
Output
—Linked List Operations—
1.Create List
2.Display List
3.Exit
Enter your choice : 1
‎
Enter the number of elements : 3
‎
Enter the value for the Node 1 : 54
‎
Enter the value for the Node 2 : 67
‎
Enter the value for the Node 3 : 23
‎
Linked list created
‎
—Linked List Operations—
1.Create List
2.Display List
3.Exit
Enter your choice : 2
‎
Elements in the list are : 54 67 23
‎
—Linked List Operations—
1.Create List
2.Display List
3.Exit
Enter your choice : 3
‎
Exiting...
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments