115 lines
2.8 KiB
C
115 lines
2.8 KiB
C
#include <stdio.h>
|
|
|
|
typedef struct Node
|
|
{
|
|
int data;
|
|
struct Node *next;
|
|
} Node;
|
|
|
|
// case 3
|
|
Node *delEle(Node *head, int data)
|
|
{
|
|
if (head == NULL)
|
|
{
|
|
printf("Linked list is empty.\n");
|
|
return NULL;
|
|
}
|
|
Node *current = head;
|
|
Node *prev = NULL;
|
|
while (current != NULL && current->data != data)
|
|
{
|
|
prev = current;
|
|
current = current->next;
|
|
}
|
|
if (current == NULL)
|
|
{
|
|
printf("Element not found in the linked list.\n");
|
|
return head;
|
|
}
|
|
if (prev == NULL)
|
|
{
|
|
head = current->next;
|
|
}
|
|
else
|
|
{
|
|
prev->next = current->next;
|
|
}
|
|
free(current);
|
|
printf("Element deleted successfully.\n");
|
|
return head;
|
|
}
|
|
|
|
// case 4
|
|
void dispList(Node *head)
|
|
{
|
|
if (head == NULL)
|
|
{
|
|
printf("Linked list is empty.\n");
|
|
return;
|
|
}
|
|
Node *current = head;
|
|
printf("Linked list elements: ");
|
|
while (current != NULL)
|
|
{
|
|
printf("%d ", current->data);
|
|
current = current->next;
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
int main()
|
|
{
|
|
Node *head = NULL;
|
|
int choice, data;
|
|
while (1)
|
|
{
|
|
printf("Choose the Linked List Operation you would like to perform:\n");
|
|
printf("1. Insert element BEFORE another element\n2. Insert element AFTER another element\n3. Delete a given element from the list\n4. Traverse the list\n5. Reverse the list\n6. Sort the list\n7. Delete every alternate node in the list\n7. Insert an element in a sorted list\n");
|
|
scanf("%d", &choice);
|
|
|
|
switch (choice)
|
|
{
|
|
case 1:
|
|
printf("Enter the value for the latest element: ");
|
|
scanf("%d", &data);
|
|
printf("Enter the number BEFORE which you would like to insert it: ");
|
|
scanf("%d", &data1);
|
|
insBef(data, data1);
|
|
break;
|
|
case 2:
|
|
printf("Enter the value for the latest element: ");
|
|
scanf("%d", &data);
|
|
printf("Enter the number AFTER which you would like to insert it: ");
|
|
scanf("%d", &data1);
|
|
insAft(data, data1);
|
|
break;
|
|
case 3:
|
|
printf("Enter the element you want to delete: ");
|
|
scanf("%d", &data);
|
|
delEle(data);
|
|
break;
|
|
case 4:
|
|
printf("List traversal");
|
|
dispList(head);
|
|
break;
|
|
case 5:
|
|
printf("The reversed link list is: ");
|
|
revList();
|
|
break;
|
|
case 6:
|
|
printf("The sorted list is: ");
|
|
sortList();
|
|
break;
|
|
case 7:
|
|
printf("The list after deleting every alternate node is:");
|
|
delAltNode();
|
|
break;
|
|
case 8:
|
|
printf("Enter the element you want to insert: ");
|
|
scanf("%d", &data);
|
|
enterSortList(data);
|
|
break;
|
|
}
|
|
}
|
|
}
|