素数筛选法<单向链表实现>

 

#include <iostream>

using namespace std;

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

class listprime
{
private:
    note *head;
public:
    listprime(int n);
    void Delete( note *p);
    void scan();
    void print();
    ~listprime();
};
listprime::~listprime()		//清理
{
    note *p=head;
    while(p)
    {
        note *q=p;
        p=p->next;
        delete q;

    }
    head =NULL;
}
listprime::listprime(int n)        //建立空链表
{
    head=new note;
    head->next=NULL;
    note *t;
    for(int i=0;i<n;i++)
    {
        t=new note;
        t->data=n-i;
        t->next=head->next;
        head->next=t;

    }
}

void listprime::print()				//输出
{
    note *hp=new note;
    hp=head->next;
    while(hp)
    {
        if(hp->data!=1)
            cout<<hp->data<<" ";
        hp=hp->next;


    }
    cout<<endl;
}
void listprime::scan()
{
    note *p=new note;
    p=head->next->next;
    while(p)
    {
        Delete(p);
        p=p->next;
    }
}
void listprime::Delete( note *p)			//筛选
{
    note *q=p;
    note *t=NULL;
    while(q->next)
    {
        if(p->next&& (q->next->data)%(p->data)==0)
        {
            t=q->next;
            q->next=q->next->next;
            delete t;

        }
        else
            q=q->next;

    }
}

int main()
{
    int n;
    cin>>n;
    listprime prime(n);
    prime.scan();
    prime.print();

    return 0;
}


 

你可能感兴趣的:(链表)