C code for inserting at middle, deleting at middle


/*Linked list first last middle insert without create function search and delete */
#include<stdio.h>
#include<malloc.h>

struct node
{
int data;
struct node *next;
};
struct node *first=NULL;
struct node *ptr=NULL;
struct node *prev=NULL;
struct node *last=NULL;


struct node *newnode=NULL;

int val,pos,count=0,i;

void insert_first();
void insert_last();
void insert_pos();
void display();
int main()
{
display();
insert_first();
insert_first();
insert_first();
display();
printf("\n");
insert_last();
insert_last();
insert_last();
display();
insert_pos();
insert_pos();
display();
printf("\n");
return 0;
}

void insert_first()
{
printf("enter a number to insert at first:\n");
scanf("%d",&val);
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;

if(first==NULL)
{
first=newnode;
first->next=NULL;
}
else
{
newnode->next=first;
first=newnode;
}
}


void display()
{
if(first==NULL)
{
printf("No element to display.\n");
}
else
{
/*for(ptr=first;ptr!=NULL;ptr=ptr->next)
{
printf("%d\t",ptr->data);
}*/
ptr=first;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}
}



void insert_last()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter a number to insert at last:\n");
scanf("%d",&newnode->data);
newnode->next=NULL;

if(first==NULL)
{
first=newnode;
}

else
{
ptr=first;
while(ptr->next!=NULL)//ptr-next is must as segflt
{
ptr=ptr->next;
}
ptr->next=newnode;
newnode->next=NULL;
}
}



void insert_pos()
{
int pos, val, cnt = 0, i;
printf("\nEnter the position:\n ");
scanf("%d", &pos);

printf("\nEnter the value for the Node:\n");
scanf("%d", &val);
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=val;
ptr = first;
while (ptr != NULL)
{
ptr = ptr->next;
cnt++;
}
if (pos == 1)
{
if (first == last && first == NULL)
{
first = last = newnode;
first->next = NULL;
last->next = NULL;
}
else
{
newnode->next=first;
first=newnode;
}
printf("\nInserted\n");
}
else if (pos>1 && pos<=cnt)
{
ptr = first;
for (i = 1;i < pos;i++)
{
prev = ptr;
ptr = ptr->next;
}
prev->next = newnode;
newnode->next = ptr;
printf("\nData inserted.\n");
}

else
{
printf("\nPosition is out of range\n");
}
}
/*
No element to display.
enter a number to insert at first:
1
enter a number to insert at first:
2
enter a number to insert at first:
3
3 2 1
enter a number to insert at last:
4
enter a number to insert at last:
5
enter a number to insert at last:
6
3 2 1 4 5 6
Enter the position:
2

Enter the value for the Node:
22

Data inserted.

Enter the position:
1

Enter the value for the Node:
11

Inserted
11 3 22 2 1 4 5 6
*/

No comments:

Post a Comment