#include <stdio.
h>
#include <stdlib.h>
// Define the structure of a node
struct Node {
int data;
struct Node* next;
};
// Function to delete the last node in the linked list
void deleteAtEnd(struct Node** head) {
// If the linked list is empty
if (*head == NULL) {
printf("The linked list is empty. No node to delete.\n");
return;
}
// If the linked list has only one node
if ((*head)->next == NULL) {
free(*head); // Free the head node
*head = NULL; // Set the head to NULL
printf("Node deleted at the end (only node in the list).\n");
return;
}
// Traverse to the second-last node
struct Node* temp = *head;
while (temp->next->next != NULL) {
temp = temp->next;
}
// Free the last node and update the second-last node's next pointer
free(temp->next); // Free the memory of the last node
temp->next = NULL; // Set the second-last node's next to NULL
printf("Node deleted at the end.\n");
}
// Function to print the linked list
void printList(struct Node* head) {
if (head == NULL) {
printf("The linked list is empty.\n");
return;
}
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to add a node at the end of the list
void append(struct Node** head, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head;
newNode->data = newData;
newNode->next = NULL;
// If the linked list is empty, make the new node the head
if (*head == NULL) {
*head = newNode;
return;
}
// Traverse to the last node
while (last->next != NULL) {
last = last->next;
}
// Change the next of last node
last->next = newNode;
}
// Main function to demonstrate deletion at the end
int main() {
struct Node* head = NULL;
// Adding elements to the linked list
append(&head, 10);
append(&head, 20);
append(&head, 30);
append(&head, 40);
printf("Linked list before deletion: ");
printList(head);
// Delete the last node
deleteAtEnd(&head);
printf("Linked list after deletion: ");
printList(head);
return 0;
}