delete even value in node

Write a program to copy the content of array to a dynamic single linked list and write a function to delete every node has an even value in its data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
using namespace std;

struct list
{
    int data;
    list *next;
};

void del_Ev(list *&head, list *&tail)
{
    list *ptr = head, *bef_tail;
    while (ptr)
    {
        if (tail->data % 2 == 0)
        {
            list *bef_ptr = ptr;
            if (tail == head)
            {
                list *node = tail;
                head = head->next;
                delete node;
                tail = tail->next;
            }
            else
            {
                list *node = tail;
                tail = tail->next;
                bef_tail->next = tail;
                delete node;
            }
        }
        else
        {
            bef_tail = tail;
            tail = tail->next;
        }
        ptr = ptr->next;
    }
}

int main()
{
    list *node = NULL, *tail = NULL, *head = NULL;
    int a[] = {1, 4, 6, 3, 7, 11, 8, 9, 10};
    for (int i = 0; i < 9; i++)
    {
        node = new list; // create new node ...
        node->data = a[i]; //set a[i] value to date element in newnode structure
        node->next = NULL; //set next to null to be end of node ...

        if (head == NULL)
        {
            head = node;
            tail = node; //set tail to piont to end of list ..
        }
        else
        {
            tail->next = node;
            tail = node;
        }
    }

    tail = head;
    // after deleting %2 = 0;
    del_Ev(head, tail);
    list *tmp = new list;
    tmp = head;
    while (tmp)
    {
        cout << tmp->data << " ";
        tmp = tmp->next;
    }
    return 0;
}


and the output is
1 3 7 11 9 Press [Enter] to close the terminal ...

but if I update the value of array to be like this
int a[] = {2, 4, 6, 3, 7, 11, 8, 9, 10};

the program didn't work well
and there wasn't any output

Sorry for my bad english
I'm confused by your use of tail. The tail of a linked list usually refers to the last element in the list or to the rest of the list after the head. I think the problem you describe is because you don't initialize bef_tail.
Peter87
I'm confused too ^_6

what do you mean by initialize ?

plz can you explain or answer the question to know what & where is my wrong?
Topic archived. No new replies allowed.