Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* head=NULL;
struct node *cn()
{
struct node* n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
void createnode() //Function to create Linked list.
{
int i,n,x;
struct node * temp,*newnode;
printf("Enter size of linked list :\n");
scanf("%d",&n);
printf("Enter elements of linked list :\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(head==NULL) //checking in linked list is empty
{
head=cn();
head->data=x;
head->next=NULL;
temp=head;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
}
}
void traverse() //Function to traverse Linked list.
{
struct node * temp;
temp=head;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
void insertnode() //Function to insert node in Linked list.
{
struct node * temp,*newnode;
int pos,i=1,x;
printf("Enter position for insertion of new node :\n");
scanf("%d",&pos);
printf("Enter value for that node :\n");
scanf("%d",&x);
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp=head;
if(head==NULL) //checking in linked list is empty
{
head=newnode;
head->next=NULL;
}
if(pos==1)
{
newnode->next=head;
head=newnode;
}
else
{
while((i<pos-1)&&(temp!=NULL))
{
temp=temp->next;
i++;
}
if(temp==NULL)
{
printf("Position out of bound.\n");
}
else
{
newnode->next=temp->next;
temp->next=newnode;
}
}
printf("node inserted\n");
}
void deletenode() //Function to delete a node from Linked list.
{
struct node * temp,*temp1;
int pos,i=1,x;
printf("Enter position for deletion :\n");
scanf("%d",&pos);
temp=head;
if(head==NULL)
{
printf("Linked list is empty. \n");
}
else if(pos==1)
{
head=head->next;
free(temp);
}
else
{
while((i<pos-1) && (temp!=NULL))
{
temp=temp->next;
i++;
}
if(temp!=NULL)
{
temp1=temp->next;
temp->next=temp1->next;
free(temp1);
}
else
{
printf("Position out of bound.\n");
}
}
}
void main()
{
int choice,a=0;
while(choice!=5)
{
printf("\n\n1. Create Linked list.\n");
printf("2. Display Linked list.\n");
printf("3. Insert node at any position.\n");
printf("4. Delete a node from any position.\n");
printf("5. Exit\n\n");
scanf("%d",&choice);
printf("\n");
switch(choice)
{
case 1: if(a==1)
{
printf("You have already created a Linked list.");
}
else
{ createnode();
a++;
}
break;
case 2: traverse();
break;
case 3: insertnode();
break;
case 4: deletenode();
break;
case 5: exit(0);
defalut: printf("Enter a valid choice\n");
}
}
}
0 Comments