I am writing a program that takes a list of integers in input, and based on the integer it performs the following operations:
remove the absolute value if the value in input is negative
If the number is positive and even, then add in on the top of the list
If the number is positive and odd, add it on the tail of the list
If the number is equal to zero, end the program and print the list.
My problem is with the pop_el function, which causes an infinite loop on the list, so when i print the list the program goes into an infinite loop. This is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct ll_node_S * ll_node_ptr;
struct ll_node_S
{
int v;
ll_node_ptr next;
};
typedef struct ll_node_S ll_node;
ll_node_ptr push_tail(ll_node_ptr head, int v)
{
ll_node_ptr backup = head;
ll_node_ptr current = head;
while(current->next != NULL)
{
current = current->next;
}
current->next = (ll_node_ptr) malloc(sizeof(ll_node));
current->v = v;
return backup;
}
ll_node_ptr push_head(ll_node_ptr head, int v)
{
ll_node_ptr new_head = (ll_node_ptr)malloc(sizeof(ll_node));
new_head->v = v;
new_head->next = head;
return new_head;
}
ll_node_ptr pop_el(ll_node_ptr head, int el)
{
ll_node_ptr backup = head;
ll_node_ptr current = head;
ll_node_ptr previous = NULL;
int found = 0;
while(current != NULL && !found)
{
if(current->v == el)
{
if(previous == NULL)
{
backup = current->next;
free(current);
current = backup;
previous = current;
}
else
{
previous->next = current ->next;
free(current);
current = current->next;
}
found = 1;
}
else
{
previous = current;
current = current->next;
}
}
return backup;
}
void print(ll_node_ptr head)
{
ll_node_ptr current = head;
printf("%d\n", head->v);
while(current->next != NULL)
{
current = current->next;
printf("%d\n", current->v);
}
}
int isPair(int n)
{
return ((n % 2) == 0);
}
int main(int argc, char** argv)
{
int n = 1;
ll_node_ptr list = NULL;
while(n != 0)
{
scanf("%d", &n);
if(n < 0)
{
list = pop_el(list, -n);
}
else
{
if(isPair(n))
{
list = push_head(list, n);
}
else
{
list = push_tail(list, n);
}
}
}
print(list);
//should free the list
return 0;
}
and this is the test case (passed in input) i am testing the code against:
4
5
2
-4
-5
-3
9
2
0
which should produce the following output:
2
2
9
any clues?