Counting even Linked List

I am trying to only count even number of nodes in a linked list and then delete them. However it doesn't count all the even number and deletes everything. Where am I messing up?



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
 #include "list.h"

using namespace std;

int countEven(node * head)
{

        node * temp = head;
        int even = 0;





        while(temp != NULL && (temp->data % 2) == 0)
        {


                even++;
                temp = temp->next;

        }
        cout << "There are " << even << " even nodes." << endl;

        return even;
}

int removeEven(node *& head)
{
        node * temp = head;
        int even = 0;

        while(temp != NULL && (temp->data % 2) == 0)
        {
                even++;
                temp = temp->next;
                delete temp;
        }

        cout << "There were " << even << " nodes deleted." << endl;

        return even;

}

Last edited on
removeEven makes no effort to keep the structure of the list in tact. You happily delete nodes without updating the nodes pointing to them. You also don't bother to update the head if it should require deletion.
Topic archived. No new replies allowed.