Skip to main content

insert node at beginning of circular linked list in c

C program for insert node at beginning of circular linked list. Here more information.

// C Program 
// Insert linked list node at beginning of 
// Circular single linked list
#include <stdio.h>
#include <stdlib.h>

struct LinkNode
{
    int data;
    struct LinkNode *next;
};
struct CircularLinkedList
{
    struct LinkNode *head;
};
// Returns the new linked list
struct CircularLinkedList *newLinkedList()
{
    // Create memory of head and tail Nodes
    struct CircularLinkedList *cll = (struct CircularLinkedList *)
    malloc(sizeof(struct CircularLinkedList));
    if (cll == NULL)
    {
        printf("Memory overflow\n");
    }
    else
    {
        cll->head = NULL;
    }
    return cll;
}
// Insert node at begining of circular linked list
void insert(struct CircularLinkedList *cll, int value)
{
    // Create a node
    struct LinkNode *node = 
      (struct LinkNode *) malloc(sizeof(struct LinkNode));
    if (node == NULL)
    {
        // Overflow
        return;
    }
    node->data = value;
    node->next = cll->head;
    if (cll->head == NULL)
    {
        // First node of linked list
        cll->head = node;
        node->next = cll->head;
    }
    else
    {
        struct LinkNode *temp = cll->head;
        // Find last node
        while (temp->next != cll->head)
        {
            // Visit to next node
            temp = temp->next;
        }
        // Add node
        temp->next = node;
        // Make new head node
        cll->head = node;
    }
}
// Display element of linked list
void display(struct LinkNode *head)
{
    if (head == NULL)
    {
        printf("Empty linked list");
    }
    else
    {
        struct LinkNode *temp = head;
        printf("Linked List Element : ");
        while (temp)
        {
            printf("%d  ", temp->data);
            // Visit to next node
            temp = temp->next;
            if (temp == head)
            {
                break; // Terminate loop
            }
        }
    }
}
int main()
{
    // Create node pointer
    struct CircularLinkedList *cll = newLinkedList();
    // insert element of linked list
    insert(cll, 8);
    insert(cll, 7);
    insert(cll, 6);
    insert(cll, 5);
    insert(cll, 4);
    insert(cll, 3);
    insert(cll, 2);
    insert(cll, 1);
    // Display all nodes
    display(cll->head);
    return 0;
}

Output

Linked List Element : 1  2  3  4  5  6  7  8




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment