Advertisement
Guest User

linear_linked_list_code

a guest
Jun 21st, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. // Write a program in C to create a linear linked list in memory to display its contents + delete the last element...
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. struct list{
  7.      int data;
  8.      struct list *next;
  9. };
  10. typedef struct list node;
  11.  
  12. void display_linked_list(node *start){
  13.  
  14.      printf("\nthe linked list is : \n");
  15.      while(start != NULL){
  16.            fflush(stdout);
  17.            printf("%d ",start->data);
  18.            start = start->next;
  19.      }
  20. }
  21.  
  22. void delete_from_linked_list(node *start){
  23.      node *temp;
  24.      temp = start;
  25.      while(temp->next->next != NULL){
  26.            temp = temp->next;
  27.      }
  28.      free(temp->next);
  29.      temp->next = NULL;
  30.      display_linked_list(start);
  31. }
  32.  
  33. int main(){
  34.     node *start,*prev,*current;
  35.     char ans;
  36.  
  37.     start = NULL;
  38.     while(1){
  39.  
  40.           printf("do you want to add a node : Y/N \n");
  41.           fflush(stdin);
  42.           scanf("%c",&ans);
  43.  
  44.           if(ans == 'Y'){
  45.              if(start == NULL){
  46.                 start = (node*)malloc(sizeof(node));
  47.  
  48.                 printf("enter data part value : \n");
  49.                 fflush(stdin);
  50.                 scanf("%d",&start->data);
  51.                 start->next = NULL;
  52.  
  53.                 prev = start;
  54.              }
  55.              else{
  56.                 current = (node*)malloc(sizeof(node));
  57.  
  58.                 printf("enter data part value : \n");
  59.                 fflush(stdin);
  60.                 scanf("%d",&current->data);
  61.                 current->next = NULL;
  62.  
  63.                 prev->next = current;
  64.                 prev = current;
  65.              }
  66.  
  67.           }
  68.           else
  69.             break;
  70.     }
  71.  
  72.     display_linked_list(start);
  73.     printf("\nafter deletion : \n");
  74.     delete_from_linked_list(start);
  75.  
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement