#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void Insert(struct Node** head, int data)
{
struct Node* current = *head;
struct Node* newNode = new Node;
if (!newNode) {
printf("\nMemory Error\n");
return;
}
newNode->data = data;
if (*head == NULL) {
newNode->next = newNode;
*head = newNode;
return;
}
else {
while (current->next != *head) {
current = current->next;
}
newNode->next = *head;
current->next = newNode;
}
}
void Display(struct Node* head)
{
struct Node* current = head;
if (head == NULL) {
printf("\nDisplay List is empty\n");
return;
}
else {
do {
printf("%d ", current->data);
current = current->next;
} while (current != head);
}
}
int Length(struct Node* head)
{
struct Node* current = head;
int count = 0;
if (head == NULL) {
return 0;
}
else {
do {
current = current->next;
count++;
} while (current != head);
}
return count;
}
void DeleteFirst(struct Node** head)
{
struct Node *previous = *head, *next = *head;
if (*head == NULL) {
printf("\nList is empty\n");
return;
}
if (previous->next == previous) {
*head = NULL;
return;
}
while (previous->next != *head) {
previous = previous->next;
next = previous->next;
}
previous->next = next->next;
*head = previous->next;
free(next);
return;
}
void DeleteLast(struct Node** head)
{
struct Node *current = *head, *temp = *head, *previous;
if (*head == NULL) {
printf("\nList is empty\n");
return;
}
if (current->next == current) {
*head = NULL;
return;
}
while (current->next != *head) {
previous = current;
current = current->next;
}
previous->next = current->next;
*head = previous->next;
free(current);
return;
}
void DeleteAtPosition(struct Node** head, int index)
{
int len = Length(*head);
int count = 1;
struct Node *previous = *head, *next = *head;
if (*head == NULL) {
printf("\nDelete Last List is empty\n");
return;
}
if (index >= len || index < 0) {
printf("\nIndex is not Found\n");
return;
}
if (index == 0) {
DeleteFirst(head);
return;
}
while (len > 0) {
if (index == count) {
previous->next = next->next;
free(next);
return;
}
previous = previous->next;
next = previous->next;
len--;
count++;
}
return;
}
int main()
{
struct Node* head = NULL;
Insert(&head;, 99);
Insert(&head;, 11);
Insert(&head;, 22);
Insert(&head;, 33);
Insert(&head;, 44);
Insert(&head;, 55);
Insert(&head;, 66);
printf("Initial List: ");
Display(head);
printf("\nAfter Deleting node at index 4: ");
DeleteAtPosition(&head;, 4);
Display(head);
printf("\n\nInitial List: ");
Display(head);
printf("\nAfter Deleting first node: ");
DeleteFirst(&head;);
Display(head);
printf("\n\nInitial List: ");
Display(head);
printf("\nAfter Deleting last node: ");
DeleteLast(&head;);
Display(head);
return 0;
}