2017-04-25 26 views
0

我想特別使用篩素數方法刪除列表中不是素數的任何數字。我有一個我一直在研究的程序,目前爲止我沒有列出任何素數,但我最終也刪除了一些素數,比如17和29等。注意我只刪除了倍數2到32. 這是我的代碼。篩選素數與鏈接列表

#include <stdio.h> 
#include <stdlib.h> 
typedef struct node{ 
    int data; 
    struct node *next; 
}node; 
node *Inserttail(node *head, int x){ 
    node *temp = (node*)malloc(sizeof(node)); 
    temp->data = x; 
    temp->next = NULL; 
    node *temp1 = head; 
    if(head==NULL) 
     return temp; 
    else if(head->next ==NULL){ 
     head ->next = temp; 
     return head; 
    } 
    while(head->next != NULL) 
     head = head->next; 
    head->next = temp; 
    return temp1; 
} 
void Print(node *head){ 
    while(head != NULL){ 
     printf(" %d", head->data); 
     head = head ->next; 
    } 
} 
node *Deletemultiples(node *head, int k){ 
    node *temp = head, *old = temp; 
    int i = 1; 
    while(temp!=NULL){ 
     if(i%k==0 && i!= k) 
      old->next = temp->next; 
     old=temp; 
     temp= temp->next; 
     i++; 
    } 
    return head; 
} 
int main(){ 
    node *head = NULL; 
    int i; 
    for(i=1; i<=1000; i++) 
     head = Inserttail(head, i); 
    for(i=2; i<=32; i++) 
     head = Deletemultiples(head, i); 
    Print(head); 
    return 0; 
} 

這是我的輸出,我現在越來越:

1 2 3 5 7 11 13 19 23 31 35 43 49 59 61 79 83 103 109 119 133 151 155 175 193 211 215 241 259 275 283 323 331 361 373 403 419 443 455 499 511 541 571 613 623 649 673 719 733 781 803 841 871 919 931 991 

,我也用現在的方法也沒有效果,我才能夠真正自由,從具體環節名單。

+2

使用'data',而不是'i' 。你也有內存泄漏。 – BLUEPIXY

+0

注:通常'1'不是素數。 – BLUEPIXY

+1

和往常一樣,[不要結果'malloc'](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –

回答

2

在你Deletemultiples功能,您具備以下條件:

int i = 1; 
while (temp != NULL) { 
    if (i % k == 0 && i != k) 
     /* … Other stuff … */ 

在這種情況下,i有你的列表中沒有任何關係,所以你不應該使用它。相反,你要看看你的node結構的data成員:

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

這會給你你正在尋找的結果:

1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 … 
+0

似乎已經奏效,謝謝。我想我是通過使用'我'來解決這個錯誤的方法,然後陷入這個想法。 –