fork(7) download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. struct node
  5. {
  6. int val;
  7. struct node *next;
  8. };
  9.  
  10. struct node *head=NULL,*last=NULL;
  11.  
  12. void insert(int value)
  13. {
  14. struct node *tmp;
  15.  
  16. tmp=(struct node *)malloc(sizeof(node));
  17.  
  18. tmp->val=value;
  19. tmp->next=NULL;
  20.  
  21. //for the first element in the list
  22. if(head==NULL)
  23. {
  24. head=tmp;
  25. last=tmp;
  26. }
  27. else
  28. {
  29. last->next=tmp;
  30. last=tmp;
  31. }
  32. }
  33.  
  34. int search(int value)
  35. {
  36. struct node* tmp=head;
  37.  
  38. while(tmp!=NULL)
  39. {
  40. if(tmp->val==value)//if found
  41. return 1;
  42.  
  43. tmp=tmp->next;
  44. }
  45.  
  46. return 0; // if not found
  47. }
  48.  
  49. void deletenode(int value)
  50. {
  51. struct node* tmp=head;
  52. struct node* prev=NULL; //pointss the previous node
  53.  
  54. while(tmp!=NULL)
  55. {
  56. if(tmp->val==value)
  57. {
  58. if(prev==NULL) // to delete the first node
  59. {
  60. head=tmp->next;
  61. }
  62. else
  63. prev->next=tmp->next;
  64.  
  65. break;
  66. }
  67.  
  68. prev=tmp;
  69. tmp=tmp->next;
  70. }
  71. }
  72.  
  73. void printlist()
  74. {
  75. struct node *tmp=head;
  76. while(tmp!=NULL)
  77. {
  78. printf("%d\n",tmp->val);
  79. tmp=tmp->next;
  80. }
  81. }
  82.  
  83. int main()
  84. {
  85. int num;
  86.  
  87. //Insert value in the list
  88. while(true)
  89. {
  90. printf("Enter value(-1 to exit): ");
  91. scanf("%d",&num);
  92.  
  93. if(num<0) break;
  94.  
  95. insert(num);
  96. }
  97.  
  98. //List printing
  99. printf("\nHere goes the list:\n");
  100. printlist();
  101.  
  102. //search a value in the list
  103. if(search(10)==1)
  104. printf("yes, the number is in the list\n");
  105. else
  106. printf("no, the number is not in the list\n");
  107.  
  108.  
  109.  
  110. //Deleting a node from the list
  111. deletenode(20);
  112. printf("\nNow the list is\n");
  113.  
  114. printlist();
  115. return 0;
  116. }
  117.  
Success #stdin #stdout 0s 2988KB
stdin
20
30
-1
stdout
Enter value(-1 to exit): Enter value(-1 to exit): Enter value(-1 to exit): 
Here goes the list:
20
30
no, the number is not in the list

Now the list is
30