C++程序设计实践指导1.13自然数集中找合数改写要求实现

改写要求1:用单链表实现

改写要求2:析构函数中依次将链表结点删除

#include <cstdlib>

#include <iostream>



using namespace std;

struct LinkNode

{

       int data;

       LinkNode* next;

};

class NOPRIME

{

      friend struct LinkNode;

      LinkNode* Head;

      int n;

      public:

            NOPRIME(int n1)

            {

               n=n1;

            }  

            void creat();

            int yes(int x)

            {

                for(int i=2;i<x/2;i++)

                   if(x%i==0)

                      return 1;

                return 0;

            }

            void Search();

            void print()

            {

                 LinkNode* p=Head->next;

                 while(p)

                 {

                         cout<<p->data<<'\t';

                         p=p->next;

                 }

                 cout<<endl;

            }

            ~NOPRIME()

            {

               LinkNode* p=Head;

               while(Head)

               {

                    p=Head;

                    Head=Head->next;

                    delete(p);

               }

            }

};



void NOPRIME::creat()

{

   Head=new LinkNode;

   Head->next=NULL;

   LinkNode* p=Head;

   int i=n;

   while(i)

   {

           LinkNode* newLinkNode=new LinkNode;

           newLinkNode->next=NULL;

           p->next=newLinkNode;

           p=newLinkNode;

           i--;

   }

}



void NOPRIME::Search()

{

     LinkNode* p;

     int i,j,t=1;

    for(i=3;;i++)

    {

       t=1;

       p=Head->next;

       for(j=i;j<i+n;j++)

        {

          p->data=j;

          p=p->next;

          if(yes(j)==0)

             t=0;

        }

    if(t==1)

       break;

    }

} 

int main(int argc, char *argv[])

{

    NOPRIME num(10);

    num.creat();

    num.Search();

    num.print();

    return EXIT_SUCCESS;

}

 

你可能感兴趣的:(程序设计)