Circularly LinkedList Insertion at the End

Algorithm

INPUT: HEADER is a pointer to the header node of the linkedlist
OUTPUT: LINKEDLIST WITH THE ADDED ELEMENT
DATA STRUCTURE: Circularly Linkedlist

STEP 1: START
STEP 2: PTR=HEADER->LINK
STEP 3: WHILE(PTR->LINK!-HEADER)DO
STEP 4: PTR=PTR->LINK
STEP 5: ENDWHILE
STEP 6: NEW=NEWNODE(NODE)
STEP 7: NEW->DATA=X
STEP 8: PTR->LINK=NEW
STEP 9: NEW->LINK=HEADER
STEP 10: END

Code

#include <stdio.h>
 #include <stdlib.h>
 int getnode(int);void display();int x, pos, n;void insertatend();
 struct node
 { int data;
    struct node *link;};
 struct node *prev, *head, *news, *p, *ptr;
 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);
    insertatend();
    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 insertatend(){
     news=malloc(sizeof(struct node));
     news->data=x;
     ptr=header->link;
     while(ptr->link!=header){
         ptr=ptr->link;
     }
     ptr->link=news;
     news->link=header;
 }
 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
1 2 3 4 5 6

Leave a Comment

Your email address will not be published. Required fields are marked *