# Inserting a Node

```c
void insert(struct node *ptr, int data, int postition) {

    // Creating a new node and assigning data
    struct node *newNode;
    newNode = (struct node *)malloc(sizeof(struct node));
    newNode -> data = data; 

    // If node is to be inserted before head
    if (position == 1) {
        // Checking if list is empty
        if (head == NULL) {
            head = newNode;
            head -> next = head;
        } 
        // If a node already exists
        else {
            // Traverse to end of list
            while (ptr -> next != head) {
                ptr = ptr -> next;
            }
            ptr -> next = newNode;
            newNode -> next = head;
        }        
    }
    
    // If node is to be inserted in any other index
    else {
        for (int i = 0; i < postition - 2; i++) {
            ptr = ptr -> next;
        }
        newNode -> next = ptr -> next;
        ptr -> next = newNode;
    }

}
```

Contributed by Nitin Ranganath


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nitinranganath.gitbook.io/data-structures/cirular-linked-list/inserting-a-node.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
