Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct stack{
- int data;
- struct stack *bottom;
- }*top = NULL;
- void push(int value){//value is to be inserted in the stack
- struct stack *newNode = (struct stack *)malloc(sizeof(struct stack));//memory for new node
- newNode->data = value; newNode->bottom = NULL;//assign values to new node
- if(top) newNode->bottom = top;//if stack is not empty, newNode's bottom points where top points
- top = newNode;//top points to the new node
- }
- void pop(){
- struct stack *target = top;//target is the top-most element in the stack
- top = top->bottom;//top points to the bottom element in the stack
- free(target);//target is freed as it's no longer needed
- }
- void display(){
- if(!help)printf("\nStack is Empty!\n");
- else{
- struct stack *help = top;
- while(help){
- printf("\t%d\n",help->data);
- help = help->bottom;
- }
- }
- }
- int main()
- {
- int n;
- while(1){
- display();
- printf(" \n1. Push 2. Pop 3. Exit\n");
- printf(" \nChoose Option: ");
- scanf("%d", &n);
- switch(n){
- case 1:
- printf("\nEnter an integer to push onto the Stack: ");
- scanf("%d",&n);
- push(n);
- break;
- case 2:
- if(top) pop();
- break;
- case 3:
- printf("\nMore programs @ pastebin.com/u/shailrshah\n");
- return 0;
- default:
- printf("\nInput Error. Try again.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement