assignment dsa
assignment dsa
h>
#include <stdlib.h>
struct Node {
int value;
struct Node* next;
};
struct Node* createList(int val) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->value = val;
newNode->next = newNode;
return newNode;
}
void addNode(struct Node** head, int val) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->value = val;
if (*head == NULL) {
newNode->next = newNode;
*head = newNode;
}
else {
struct Node* temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = *head;
}
}
void removeNode(struct Node** head, int val) {
if (*head == NULL) return;
struct Node *curr = *head, *prev = NULL;
if (curr->value == val) {
if (curr->next == *head) {
free(curr);
*head = NULL;
return;
}
while (curr->next != *head) {
curr = curr->next;
}
curr->next = (*head)->next;
free(*head);
*head = curr->next;
return;
}
curr = *head;
do {
prev = curr;
curr = curr->next;
if (curr->value == val) {
prev->next = curr->next;
free(curr);
return;
}
} while (curr != *head);
}
void showList(struct Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
do {
printf("%d -> ", temp->value);
temp = temp->next;
} while (temp != head);
printf("(Back to Head)\n");
}
int main() {
struct Node* head = NULL;
int n, val, choice, delVal;
printf("How many nodes do you want to insert? ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter value for node %d: ", i + 1);
scanf("%d", &val);
if (head == NULL) {
head = createList(val);
} else {
addNode(&head, val);
}
}
printf("Circular Linked List after insertion:\n");
showList(head);
while (1) {
printf("\nChoose an option:\n");
printf("1. Delete a node\n");
printf("2. Display list\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to delete: ");
scanf("%d", &delVal);
removeNode(&head, delVal);
printf("Updated list:\n");
showList(head);
break;
case 2:
printf("Current list:\n");
showList(head);
break;
case 3:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}