Algorithm
INPUT: HEADER is a pointer to the header node of the linkedlist and the position where the element is to be inserted
OUTPUT: LINKEDLIST WITH THE ADDED ELEMENT
DATA STRUCTURE: Circularly Linkedlist
STEP 1: START
STEP 2: PTR=HEADER->LINK
STEP 3: FOR( I=1 TO POS ) DO
STEP 4: PTR1=PTR
STEP 5: PTR=PTR->LINK
STEP 6: ENDFOR
STEP 7: NEW=NEWNODE(NODE)
STEP 8: PTR1->LINK=NEW
STEP 9: NEW->LINK=PTR
STEP 10: END
Code
#include <stdio.h>
#include <stdlib.h>
int getnode(int);void display();int x, pos, n;void insertatany();
struct node
{ int data;
struct node *link;};
struct node *prev, *head, *news, *p, *ptr,*ptr1;
struct node *q1;
struct node *header, *header1;
struct node *q, *r, *s;
int main(){
printf("ENTER THE LIMIT ");
scanf("%d", &n);
getnode(n);
printf("ENTER THE ELEMENT WANT TO INSERT:");
scanf("%d",&x);
printf("ENTER THE POSITION WHERE YOU WANT TO INSERT:");
scanf("%d",&pos);
insertatany();
display(header);
return 0;
}
void display(struct node *head1)
{
struct node *ptr;
ptr = head1->link;
// ptr=header->link;
while (ptr != header)
{
printf("%d ", ptr->data);
ptr = ptr->link;
}
}
void insertatany(){
news=malloc(sizeof(struct node));
news->data=x;
ptr=header->link;
for(int i=1;i<pos;i++)
{
ptr1=ptr;
ptr=ptr->link;
}
ptr1->link=news;
news->link=ptr;
}
int getnode(int n)
{
header = malloc(sizeof(struct node));
head = NULL;
for (int i = 0; i < n; i++)
{
p = malloc(sizeof(struct node));
scanf("%d", &p->data);
p->link = NULL;
if (head == NULL)
head = p;
else
prev->link = p;
prev = p;
}
p->link=header;
header->link = head;
display(header);
return 0;
}
Output
user@computer$ : ENTER THE LIMIT 5
1
2
3
4
5
1 2 3 4 5 ENTER THE ELEMENT WANT TO INSERT:6
ENTER THE POSITION WHERE YOU WANT TO INSERT:2
1 6 2 3 4 5