Skip to main content

Effectively insert node at beginning of circular linked list in c

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

// C Program 
// Insert linked list node at beginning of 
// circular single linked list
// Using head and tail pointer

#include <stdio.h>
 // for malloc function
#include <stdlib.h>

struct LinkNode
{
    int data;
    struct LinkNode *next;
};
struct CircularLinkedList
{
    struct LinkNode *head;
    struct LinkNode *tail;
};
// 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;
        cll->tail = NULL;
    }
    return cll;
}
// Insert node at begining of circular linked list
void insert(struct CircularLinkedList *cll, int value)
{
    // Create a new node
    struct LinkNode *node = 
      (struct LinkNode *) malloc(sizeof(struct LinkNode));
    if (node == NULL)
    {
        // Overflow
        return;
    }
    node->data = value;
    node->next = cll->head;
    if (cll->tail == NULL)
    {
        // First node of linked list
        cll->tail = node;
    }
    // Make new head
    cll->head = node;
    cll->tail->next = 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();
    // Add 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