Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6. int info;
  7. struct node *next;
  8. };
  9. typedef struct node node;
  10.  
  11. node *inserthead(node *head, int a){
  12. node *ptr;
  13. ptr = (node*)malloc(sizeof(node));
  14. ptr->info = a;
  15. ptr->next = head;
  16. return(ptr);
  17. }
  18.  
  19. node *deletemultiples(node *head, int k){
  20. node *ptrcur = head, *ptrlast = ptrcur, *deletethis;
  21. while (ptrcur != NULL){
  22. if(ptrcur->info != k && ptrcur->info%k == 0){
  23. ptrlast->next = ptrcur->next;
  24. deletethis = ptrcur;
  25. ptrlast = ptrcur;
  26. ptrcur = ptrcur->next;
  27. free(deletethis);
  28. }
  29. else{
  30. ptrlast = ptrcur;
  31. ptrcur = ptrcur->next;
  32. }
  33. }
  34. return(head);
  35. }
  36.  
  37. void printlist (node *head){
  38. while (head != NULL){
  39. if (head->next != NULL)
  40. printf("%d, ", head->info);
  41. if (head->next == NULL)
  42. printf("%d",head->info);
  43. head = head->next;
  44. }
  45. printf("\n");
  46. }
  47.  
  48. void freelist (node *head){
  49. node *del = head;
  50. while(head != NULL) {
  51. head = head->next;
  52. free(del);
  53. del = head;
  54. }
  55. }
  56.  
  57. int main(){
  58. int i;
  59. node *head = NULL;
  60.  
  61. // This for loop creates the initial list of all integers 2-1000.
  62. for (i = 1000; i > 1; i--){
  63. head = inserthead(head, i);
  64. }
  65.  
  66. // This deletes all multiples of all numbers between 1-32 from the list.
  67. if(head != NULL){
  68. for (i = 2; i <= 32; i++){
  69. deletemultiples(head, i);
  70. }
  71.  
  72. // This prints the list, which should be the primes.
  73. printlist(head);
  74. freelist(head);
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement