PROGRAM 9A
PROGRAM 9A
struct Node
{
int data;
struct Node* next;
};
struct Node* createNode(int value)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
void insert(struct Node** head, int value)
{
struct Node* newNode = createNode(value);
struct Node* temp;
if (*head == NULL)
{
*head = newNode;
}
else
{
temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
}
void deleteNode(struct Node** head, int value)
{
struct Node* current;
struct Node* previous;
if (*head == NULL)
{
printf("List is empty. Deletion not possible.\n");
return;
}
if ((*head)->data == value)
{
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
printf("Node with value %d deleted.\n", value);
return;
}
current = *head;
previous = NULL;
while (current != NULL && current->data != value)
{
previous = current;
current = current->next;
}
if (current != NULL)
{
previous->next = current->next;
free(current);
printf("Node with value %d deleted.\n", value);
}
else
{
printf("Value %d not found in the list.\n", value);
}
}
int search(struct Node* head, int value)
{
struct Node* current;
current = head;
while (current != NULL)
{
if (current->data == value)
{
return 1;
}
current = current->next;
}
return 0;
}
void traverse(struct Node* head)
{
struct Node* current;
current = head;
if (current == NULL)
{
printf("List is empty.\n");
return;
}
while (current != NULL)
{
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main()
{
struct Node* head = NULL;
int choice, value;
clrscr();
while (1)
{
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Search\n");
printf("4. Traverse\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
insert(&head, value);
break;
case 2:
printf("Enter value to delete: ");
scanf("%d", &value);
deleteNode(&head, value);
break;
case 3:
printf("Enter value to search: ");
scanf("%d", &value);
if (search(head, value) == 1)
{
printf("Value %d found in the list.\n", value);
}
else
{
printf("Value %d not found in the list.\n", value);
}
break;
case 4:
printf("List: ");
traverse(head);
break;
case 5:
printf("Exiting...\n");
getch();
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}
}