程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++程序設計實踐指導1.13自然數集中找合數改寫要求實現,程序設計實踐1.13

C++程序設計實踐指導1.13自然數集中找合數改寫要求實現,程序設計實踐1.13

編輯:C++入門知識

C++程序設計實踐指導1.13自然數集中找合數改寫要求實現,程序設計實踐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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved