DSA Ex5
DSA Ex5
h>
#include<stdlib.h>
#include<stdbool.h>
struct node{
int data;
struct node *next;
} *head = NULL, *temp;
void insertAtBeg()
{
struct node* new_Node = (struct node*)malloc(sizeof(struct node));
printf("Enter Data to Insert: ");
scanf("%d", &new_Node->data);
if(head == NULL)
{
head = new_Node;
new_Node->next = NULL;
}
else
{
new_Node->next = head;
head = new_Node;
}
}
void insertAtEnd()
{
if(head == NULL)
{
printf("List is Empty");
}
else
{
struct node* last_Node = (struct node*)malloc(sizeof(struct node));
printf("Enter Data to Insert: ");
scanf("%d", &last_Node->data);
temp = head;
while(temp->next!= NULL)
{
temp = temp->next;
}
temp->next= last_Node;
last_Node->next = NULL;
}
}
void insertAtMiddle(){
int ctr = 0;
int middle, i = 0;
temp = head;
strct node *temp1;
struct node* middle_Node = (struct node*)malloc(sizeof(struct node));
printf("Enter Data to Insert: ");
scanf("%d", &middle_Node->data);
while(temp!= NULL)
{
ctr++;
}
if(ctr%2 == 0)
middle = ctr/2;
else
middle = (ctr/2)+1;
while(i<middle)
{
temp = temp->next;
}
temp1 = temp->next;
temp->next = middle_Node;
middle_Node->next = temp1;
}
void display()
{
printf("Elements in Linked list are: ");
temp = head;
while(temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
int main()
{
int choice;
while(true)
{
printf("\nChoose Option\n 1- Insert@Begning\t2- Insert@Middle\n 3- Insert@End\
t4- Exit");
printf("\nEnter Choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insertAtBeg();
break;
/*case 2:
insertAtMiddle();
break;*/
case 3:
insertAtEnd();
break;
case 4:
display();
exit(1);
}
}
}