Advertisement
NabilaShova

DS Lab 5-Stack with Linked List

Jul 27th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5.     int data;
  6.     struct node *next;
  7. }*head;
  8.  
  9. int count()
  10. {
  11.     struct node *temp;
  12.     temp = head;
  13.     int c=0;
  14.     while(temp != NULL)
  15.     {
  16.         c++;
  17.         temp = temp->next;
  18.     }
  19.     return c;
  20. }
  21.  
  22. void display()
  23. {
  24.     struct node *temp;
  25.     temp = head;
  26.     if(temp == NULL)
  27.         printf("List is empty\n");
  28.     else
  29.     {
  30.         while(temp != NULL)
  31.         {
  32.             printf("%d ", temp->data);
  33.             temp = temp->next;
  34.         }
  35.         printf("\n");
  36.     }
  37. }
  38.  
  39. void push(int num)
  40. {
  41.     struct node *temp;
  42.     temp=(struct node*)malloc(sizeof(struct node));
  43.  
  44.     temp->data=num;
  45.  
  46.     if(head==NULL){
  47.         head=temp;
  48.         temp->next=NULL;
  49.     }
  50.     else{
  51.         temp->next=head;
  52.         head=temp;
  53.     }
  54. }
  55.  
  56.  
  57. void delete()
  58. {
  59.     struct node *temp;
  60.     temp = head;
  61.     head = temp->next;
  62.     free(temp);
  63.     printf("Delete successful\n");
  64. }
  65. int main()
  66. {
  67.     int n, op, x;
  68.     struct node *temp;
  69.     while(1)
  70.     {
  71.         printf("\n1.Insert\n");
  72.         printf("2.Display\n");
  73.         printf("3.Size\n");
  74.         printf("4.Delete\n");
  75.         printf("5.Exit\n");
  76.         printf("Enter your choice: ");
  77.         scanf("%d", &op);
  78.         if(op == 1)
  79.         {
  80.             printf("Enter number to insert: ");
  81.             scanf("%d", &n);
  82.             push(n);
  83.         }
  84.         else if(op == 2)
  85.         {
  86.             printf("Element(s) in the list are: ");
  87.             display();
  88.         }
  89.         else if(op == 3)
  90.         {
  91.             printf("Size of the list is: %d", count());
  92.         }
  93.         else if(op == 4)
  94.         {
  95.             if(head == NULL)
  96.                 printf("List is empty!\n");
  97.             else
  98.             {
  99.                 delete();
  100.             }
  101.         }
  102.         else if(op == 5)
  103.             break;
  104.         else
  105.             printf("Invalid option\n");
  106.     }
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement