Algorithm for Inserting in an Ordered Circular Linked List
Algorithm for Inserting in an Ordered Circular Linked List
2. If the list is empty, make the new node point to itself and set it as the head.
4. Otherwise:
o Traverse the list to find the correct position where the new node should be inserted.
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
};
newNode->data = data;
// If the list is empty
if (*head == NULL) {
*head = newNode;
return;
current = current->next;
// Adjust pointers
current->next = newNode;
newNode->next = *head;
*head = newNode;
return;
do {
prev = current;
current = current->next;
prev->next = newNode;
newNode->next = current;
if (head == NULL) {
printf("List is empty\n");
return;
do {
temp = temp->next;
printf("(Head)\n");
// Main function
int main() {
insertInOrder(&head, 30);
insertInOrder(&head, 10);
insertInOrder(&head, 40);
insertInOrder(&head, 20);
insertInOrder(&head, 25);
// Display list
display(head);
return 0;
Explanation
o If the list is empty, make the new node’s next point to itself.
Output