C function that deletes all nodes from a linked list with even values? The progr
ID: 3891194 • Letter: C
Question
C function that deletes all nodes from a linked list with even values?
The program has to actually free the nodes not just bypass them.
For example: the input- {2, 2, 2, 1, 2, 2, 7, 9} should return 1, 7, 9.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *create_node(int data)
{
node *ptr = malloc(sizeof(node));
if (ptr == NULL)
{
fprintf(stderr, "Error: Out of memory in create_node() ");
exit(1);
}
ptr->data = data;
ptr->next = NULL;
return ptr;
}
node *tail_insert(node *head, int data)
{
node *temp;
if (head == NULL)
return create_node(data);
for (temp = head; temp->next != NULL; temp = temp->next)
;
temp->next = create_node(data);
return head;
}
void print_list(node *head)
{
node *temp;
if (head == NULL)
{
printf("(empty list) ");
return;
}
for (temp = head; temp != NULL; temp = temp->next)
printf("%d%c", temp->data, (temp->next == NULL) ? ' ' : ' ');
}
int main(void)
{
int i;
int a[] = {2, 2, 2, 1, 2, 2, 7, 9};
node *head = NULL;
for (i = 0; i < 8; i++)
head = tail_insert(head, a[i]);
print_list(head);
printf(" ");
return 0;
}
Explanation / Answer
C Program:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *create_node(int data)
{
node *ptr = malloc(sizeof(node));
if (ptr == NULL)
{
fprintf(stderr, "Error: Out of memory in create_node() ");
exit(1);
}
ptr->data = data;
ptr->next = NULL;
return ptr;
}
node *tail_insert(node *head, int data)
{
node *temp;
if (head == NULL)
return create_node(data);
for (temp = head; temp->next != NULL; temp = temp->next);
temp->next = create_node(data);
return head;
}
void print_list(node *head)
{
node *temp;
if (head == NULL)
{
printf("(empty list) ");
return;
}
for (temp = head; temp != NULL; temp = temp->next)
printf("%d%c", temp->data, (temp->next == NULL) ? ' ' : ' ');
}
void removeEven(node **head)
{
node *temp, *odd;
//if empty
if (head == NULL)
{
printf("(empty list) ");
return;
}
temp = *head; //assign head to temp
//loop till we find odd number
while(temp != NULL && temp->data % 2 == 0)
temp = temp->next;
*head = temp; //new head
//if NULL return
if(temp == NULL)
return;
odd = temp; //current odd element
temp = temp->next; //move to next node
//loop till end
while(temp != NULL)
{
//if odd
if(temp->data%2 != 0)
{
odd->next = temp; //next node
odd = temp; //current node
}
//next node
temp = temp->next;
}
odd->next = NULL; //end node
}
int main(void)
{
int i;
int a[] = {2, 2, 2, 1, 2, 2, 7, 9};
node *head = NULL;
for (i = 0; i < 8; i++)
head = tail_insert(head, a[i]);
removeEven(&head);
print_list(head);
printf(" ");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.