my code works fine i checked it out, its work with deleting the front
only
You are wrong. This code snippet
else if (temp == *front) { //if odd num founded @ the begining of the doubly linked list!
oddnum = (*front)->data;
*front = (*front)->next;
(*front)->previous = NULL;
free(temp);
}
can invoke undefined behavior when the list contains only one node because after this statement
*front = (*front)->next;
the pointer front
will be equal to NULL and you may not use this null pointer in the following statement
(*front)->previous = NULL;
The function can be defined the following way. I suppose that if such a node with an odd value is found when the stored value is returned. Otherwise -1 is returned.
int DeleteFirstODD( Node **front )
{
int oddnum = -1;
Node *temp = *front;
while ( temp != NULL && temp->data % 2 == 0 )
{
temp = temp->next;
}
if ( temp != NULL )
{
oddnum = temp->data;
if ( temp == *front )
{
if ( temp->next != NULL )
{
temp->next->previous = temp->previous;
}
*front = temp->next;
}
else if ( temp->next == NULL )
{
temp->previous->next = temp->next;
}
else
{
temp->previous->next = temp->next;
temp->next->previous = temp->previous;
}
free( temp );
}
return oddnum;
}
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
struct Node *previous;
} Node;
int push_front( Node **head, int data )
{
Node *new_node = malloc( sizeof( Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = data;
new_node->next = *head;
if ( *head ) ( *head )->previous = new_node;
new_node->previous = NULL;
*head = new_node;
}
return success;
}
void display( const Node *head )
{
for ( ; head; head= head->next )
{
printf( "%d -> ", head->data );
}
puts( "null" );
}
int DeleteFirstODD( Node **front )
{
int oddnum = -1;
Node *temp = *front;
while ( temp != NULL && temp->data % 2 == 0 )
{
temp = temp->next;
}
if ( temp != NULL )
{
oddnum = temp->data;
if ( temp == *front )
{
if ( temp->next != NULL )
{
temp->next->previous = temp->previous;
}
*front = temp->next;
}
else if ( temp->next == NULL )
{
temp->previous->next = temp->next;
}
else
{
temp->previous->next = temp->next;
temp->next->previous = temp->previous;
}
free( temp );
}
return oddnum;
}
int main(void)
{
Node *head = NULL;
const int N = 10;
for ( int i = N; i != 0; i-- )
{
push_front( &head, i );
}
display( head );
for ( int num; ( num = DeleteFirstODD( &head ) ) != -1; )
{
printf( "The value of the deleted node is %d\n", num );
display( head );
}
return 0;
}
The program output is
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null
The value of the deleted node is 1
2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null
The value of the deleted node is 3
2 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null
The value of the deleted node is 5
2 -> 4 -> 6 -> 7 -> 8 -> 9 -> 10 -> null
The value of the deleted node is 7
2 -> 4 -> 6 -> 8 -> 9 -> 10 -> null
The value of the deleted node is 9
2 -> 4 -> 6 -> 8 -> 10 -> null