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
,我也用現在的方法也沒有效果,我才能夠真正自由,從具體環節名單。
使用'data',而不是'i' 。你也有內存泄漏。 – BLUEPIXY
注:通常'1'不是素數。 – BLUEPIXY
和往常一樣,[不要結果'malloc'](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –