Untitled
unknown
c_cpp
a year ago
2.3 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> // Node structure for the linked list struct Node { int data; 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->next = NULL; return newNode; } // Function to append a new node to the end of the linked list void append(struct Node** head, int data) { struct Node* newNode = createNode(data); if (*head == NULL) { *head = newNode; return; } struct Node* temp = *head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; } // Function to delete nodes with even numbers from the linked list void deleteEvenNodes(struct Node** head) { struct Node* current = *head; struct Node* prev = NULL; while (current != NULL) { if (current->data % 2 == 0) { // Node has even data, delete it if (prev == NULL) { // Node to be deleted is the head *head = current->next; free(current); current = *head; } else { // Node to be deleted is not the head prev->next = current->next; free(current); current = prev->next; } } else { // Node has odd data, move to the next node prev = current; current = current->next; } } } // Function to print the linked list void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } // Main function to test deleting even nodes from the linked list int main() { struct Node* head = NULL; // Example data for the linked list append(&head, 5); append(&head, 2); append(&head, 9); append(&head, 4); append(&head, 6); printf("Original linked list: "); printList(head); deleteEvenNodes(&head); printf("Linked list after deleting even nodes: "); printList(head); return 0; } /* Original linked list: 5 2 9 4 6 Linked list after deleting even nodes: 5 9 */
Editor is loading...
Leave a Comment