mardi 24 novembre 2015

Linked list accessing the value

I'm working on a linked list assignment, which is about sieve of Eratosthenes. My program works as I intended except an error. The program includes a function that makes the value of each node 0 unless the node's value is a prime number. However, it doesn't access to the last node. Can anyone give advice?

template <typename T>
class node
{
public:
    T nodeValue;
    node<T> *next;
    node() : next(NULL)
    {}
    node(const T& item, node<T> *nextNode = NULL) :
        nodeValue(item), next(nextNode)
    {}
};

above is header file.

#include <iostream>
#include <list>
#include "d_node.h"

using namespace std;

template <typename T>
void writeLinkedList(node<T> *front, const string& separator = " ")
{
    node<T> *curr;
    curr = front;

    while (curr != NULL)
    {
        if(curr->nodeValue != 0 && curr->nodeValue != 1)
        {
            cout << curr->nodeValue << " ";
        }
        curr = curr->next;
    }
}

template <typename T>
void makeZero(node<T> *front, const T& item)
{
    node<T> *curr;
    curr = front;

    while (curr != NULL)
    {
        if (curr->nodeValue == item)
        {
            curr->nodeValue = 0;
        }
        curr = curr->next;
    }

}

int main() {

int i;
cout << "Enter an integer: ";
cin >> i;

node<int> *front = NULL, *newNode;

newNode = new node<int> (1, front);
front = newNode;

for (int k = i; 0 < k; k--)
{
    newNode = new node<int> (k, front);
    front = newNode;
}

for (int a = 2; a < 1000; a++)
{
    for (int b = 2; a*b < i; b++)
    {
        int count = a*b;
        makeZero(front, count);
    }
}

writeLinkedList(front, " ");
cout << endl;
}

And above is the main file

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire