#include <stdio.h>
#include <stdlib.h>
// Structure for a Node in Circular Doubly Linked List
struct Node
{
int data;
struct Node* prev;
struct Node* next;
};
// Function to create a new Node
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Function to insert a Node at the end of the Circular Doubly Linked List
struct Node* insertEnd(struct Node* head, int data)
{
struct Node* newNode = createNode(data);
if (head == NULL)
{
newNode->prev = newNode;
newNode->next = newNode;
return newNode;
}
newNode->prev = head->prev;
newNode->next = head;
head->prev->next = newNode;
head->prev = newNode;
return head;
}
// Function to display Circular Doubly Linked List
void display(struct Node* head)
{
if (head == NULL)
{
printf("List is empty.\n");
return;
}
struct Node* current = head;
do
{
printf("%d ", current->data);
current = current->next;
} while (current != head);
printf("\n");
}
void main()
{
struct Node* head = NULL;
int n, data;
printf("Enter the number of nodes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("Enter data for node %d: ", i + 1);
scanf("%d", &data);
head = insertEnd(head, data);
}
printf("Circular Doubly Linked List: ");
display(head);
}
// Structure for a Node in Circular Doubly Linked List
struct Node
{
int data;
struct Node* prev;
struct Node* next;
};
// Function to create a new Node
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Function to insert a Node at the end of the Circular Doubly Linked List
struct Node* insertEnd(struct Node* head, int data)
{
struct Node* newNode = createNode(data);
if (head == NULL)
{
newNode->prev = newNode;
newNode->next = newNode;
return newNode;
}
newNode->prev = head->prev;
newNode->next = head;
head->prev->next = newNode;
head->prev = newNode;
return head;
}
// Function to display Circular Doubly Linked List
void display(struct Node* head)
{
if (head == NULL)
{
printf("List is empty.\n");
return;
}
struct Node* current = head;
do
{
printf("%d ", current->data);
current = current->next;
} while (current != head);
printf("\n");
}
void main()
{
struct Node* head = NULL;
int n, data;
printf("Enter the number of nodes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("Enter data for node %d: ", i + 1);
scanf("%d", &data);
head = insertEnd(head, data);
}
printf("Circular Doubly Linked List: ");
display(head);
}
Output:
Enter the number of nodes: 4
Enter data for node 1: 5
Enter data for node 2: 6
Enter data for node 3: 1
Enter data for node 4: 8
Circular Doubly Linked List: 5 6 1 8
No comments:
Post a Comment