fork download
  1. //deleting the last node of a linked list
  2. // here we use two pointer for deletion temp points last node
  3. //and temp 2 points 2nd last node
  4. //because we need to assign NULL to the link part of the 2nd last node
  5. //temp2->link = NULL;
  6. // temp used to free the last node(free(temp);,temp=NULL)
  7. #include<stdio.h>
  8. #include<stdlib.h>
  9.  
  10. struct Node {
  11. int data;
  12. struct Node* link;
  13. };
  14. typedef struct Node node;
  15.  
  16. node* del_last(node*head){
  17. if(head==NULL)
  18. // if there is no node in the list
  19. printf("list is alredy empty\n");
  20. else if (head->link==NULL) {
  21. // if there is one node in the list
  22. free(head);
  23. head=NULL;
  24. }
  25. else{
  26. node* temp=head;
  27. node* temp2=head;
  28. while(temp->link!=NULL){
  29. temp2=temp;
  30. temp=temp->link;
  31. }
  32. temp2->link=NULL;
  33. free(temp);
  34. temp=NULL;
  35. }
  36. return head;
  37.  
  38. }
  39.  
  40. int main(){
  41. node* head=malloc(sizeof(node));
  42. head->data=0;
  43. head->link=NULL;
  44.  
  45. node*ptr=malloc(sizeof(node));
  46. ptr->data=1;
  47. ptr->link=NULL;
  48. head->link=ptr;
  49.  
  50. node*ptr2=malloc(sizeof(node));
  51. ptr2->data=2;
  52. ptr2->link=NULL;
  53. ptr->link=ptr2;
  54.  
  55. head=del_last(head);
  56.  
  57.  
  58.  
  59. ptr=head;
  60. while(ptr!=NULL){
  61. printf("%d ",ptr->data);
  62. ptr=ptr->link;
  63. }
  64.  
  65.  
  66. }
  67.  
  68.  
Success #stdin #stdout 0s 5520KB
stdin
Standard input is empty
stdout
0 1