fork download
  1.  
  2. /******************************************************************************
  3.  
  4.   Online C Compiler.
  5.   Code, Compile, Run and Debug C program online.
  6. Write your code in this editor and press "Run" button to compile and execute it.
  7.  
  8. *******************************************************************************/
  9.  
  10. #include <stdio.h>
  11. #include<stdlib.h>
  12.  
  13. struct node {
  14. int data;
  15. struct node *next;
  16. };
  17.  
  18.  
  19. struct node* insert(struct node* node, int data){
  20. if(node == NULL){
  21. struct node *temp = (struct node*)malloc(sizeof(struct node));
  22.  
  23. temp->data = data;
  24. temp->next = NULL;
  25.  
  26. return temp;
  27. }else {
  28. node->next = insert(node->next, data);
  29.  
  30. }
  31. return node;
  32. }
  33.  
  34.  
  35. void print(struct node* head){
  36. while(head != NULL){
  37. printf("%d\n", head->data);
  38. head = head->next;
  39. }
  40. printf("\n\n");
  41. }
  42.  
  43.  
  44. struct node* delete(struct node* node, int data){
  45.  
  46. struct node* prev = NULL;
  47. struct node* temp = NULL;
  48. while(node != NULL) {
  49. if(node->data != data){
  50. prev = node;
  51. node = node->next;
  52. } else {
  53. if(node->next == NULL) {
  54. temp = node;
  55. prev->next = NULL;
  56. break;
  57. } else {
  58. temp = node->next;
  59. *node = *temp;
  60. }
  61. free(temp);
  62. }
  63. }
  64. }
  65.  
  66. int main()
  67. {
  68. struct node* head = NULL;
  69. head = insert(head, 6);
  70. insert(head, 2);
  71. insert(head, 6);
  72. insert(head, 4);
  73. insert(head, 1);
  74. insert(head, 4);
  75. insert(head, 5);
  76. insert(head, 8);
  77. insert(head, 6);
  78.  
  79. print(head);
  80.  
  81. delete(head, 6);
  82.  
  83. print(head);
  84.  
  85. return 0;
  86. }
  87.  
Success #stdin #stdout 0s 5280KB
stdin
45
stdout
6
2
6
4
1
4
5
8
6


2
4
1
4
5
8