• Register

For inserting node at first in circular linked list in C.We must know the steps or pseudo code about insertion a node at first .

Pseudo Code

  1. Take a ptr node and assign data to it .
  2. Make a p node and assign head->next to it and iterate all over the list until p->next != head.
  3. When we reached at last then ptr->next points to head and p->next points to ptr.
  4. Then assign the head to ptr because ptr will be the new head.

Actual Code 

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node *next; //self referencing node
};

void linkedListTransversal(struct Node *head)
{   struct Node *ptr=head;
    do
    {
        printf("Element:%d\n", ptr->data);
        ptr = ptr->next;
    }while(ptr!=head);
}
//case 1
struct Node * insertionAtFirst(struct Node *head,int data){
    struct Node *ptr=(struct Node *)malloc(sizeof(struct Node));
    ptr->data=data;
    struct Node *p=head->next;
    while(p->next!=head){
        p=p->next;
    }
    p->next=ptr;
    ptr->next=head;
    head=ptr;
    return ptr;
}


int main()
{

    struct Node *head;
    struct Node *second;
    struct Node *third;
    struct Node *fourth;
    head = (struct Node *)malloc(sizeof(struct Node));
    second = (struct Node *)malloc(sizeof(struct Node));
    third = (struct Node *)malloc(sizeof(struct Node));
    fourth = (struct Node *)malloc(sizeof(struct Node));

    head->data = 10;
    head->next = second;

    second->data = 20;
    second->next = third;

    third->data = 30;
    third->next = fourth;

    fourth->data = 40;
    fourth->next = head;

    linkedListTransversal(head);
    printf("\n");
    head = insertionAtFirst(head,5);
    printf("\n");
    linkedListTransversal(head);
    return 0;
}

 

100 points
5

1 Comment

Thank you so much for your valuable input. kodlogs is my all time favourite platform to seek guidance .

Much aprreciated!!