Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- struct stack{
- int data;
- struct stack*next;
- };
- struct stack* top=NULL;//GLOBAL VARIABLE
- bool is_empty()
- {
- return (top==NULL);
- }
- void push(int data)
- {
- struct stack *temp=(struct stack*)malloc(sizeof(struct stack ));
- temp->data=data;
- if(is_empty())
- {
- top=temp;
- temp->next=NULL;
- }
- else
- {
- temp->next=top;
- top=temp;
- }
- }
- void pop()
- {
- if(is_empty())
- {
- printf("The stack is empty\n");
- return;
- }
- struct stack *temp=top;
- top=temp->next;
- temp->next=NULL;
- }
- void traverse()
- {
- struct stack *ptr=top;
- if(is_empty())
- {
- printf("The stack is empty.\n\n");
- return;
- }
- while(ptr!=NULL)
- {
- printf("%d",ptr->data);
- printf(" ");
- ptr=ptr->next;
- }
- printf("\n");
- }
- int size()
- {
- int length=0;
- struct stack* temp=top;
- while(temp!=NULL)
- {
- length++;
- temp=temp->next;
- }
- return length;
- }
- int top_element()
- {
- int x=top->data;
- return x;
- }
- void print()
- {
- printf("Stack Operations.\n");
- printf("1. Insert into stack (Push operation).\n");
- printf("2. Delete from stack (Pop operation).\n");
- printf("3. Print top element of stack.\n");
- printf("4. Check if stack is empty.\n");
- printf("5. Traverse stack.\n");
- printf("6. Size.\n");
- printf("7. Exit.\n");
- printf("Enter your choice.\n");
- }
- int main()
- {
- int choice;
- while(1)
- {
- print();
- scanf("%d",&choice);
- if(choice==1)
- {
- printf("Enter the data you want to insert:");
- int data;
- scanf("%d",&data);
- push(data);
- }
- else if(choice==2)
- {
- pop();
- }
- else if(choice==3)
- {
- if(is_empty())
- {
- printf("The stack is empty\n");
- }
- else
- {
- int topelm=top_element();
- printf("%d\n",topelm);
- }
- }
- else if(choice==4)
- {
- if(is_empty())
- {
- printf("The stack is empty\n");
- }
- else
- {
- printf("The stack isn't empty\n");
- }
- }
- else if(choice==5)
- {
- traverse();
- }
- else if(choice==6)
- {
- int siz=size();
- printf("size is %d\n",siz);
- }
- else if(choice==7)
- {
- break;
- }
- }
- }
Add Comment
Please, Sign In to add comment