0% found this document useful (0 votes)
21 views

DSA Ex5

This C program defines functions to insert nodes into a linked list at different positions - beginning, middle, and end. It uses a while loop to continuously prompt the user for an option to insert or display the list until exiting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

DSA Ex5

This C program defines functions to insert nodes into a linked list at different positions - beginning, middle, and end. It uses a while loop to continuously prompt the user for an option to insert or display the list until exiting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include<stdio.

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);
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy