Sunday 6 November 2016

Data Structure & Algorithms | Stack

DATA STRUCTURE

STACK

A stack is a basic data structure that can be logically thought as linear structure represented by a real physical stack or pile, a structure where insertion and deletion of items takes place at one end called top of the stack. The basic concept can be illustrated by thinking of your data set as a stack of plates or books where you can only take the top item off the stack in order to remove things from it. This structure is used all throughout programming.
The basic implementation of a stack is also called a LIFO (Last In First Out) to demonstrate the way it accesses data, since as we will see there are various variations of stack implementations.
There are basically three operations that can be performed on stacks . They are 1) inserting an item into a stack (push). 2) deleting an item from the stack (pop). 3) displaying the contents of the stack(pip).

#include<stdio.h>
#include<stdlib.h>
#define Max 5
int a[Max];
int top=-1;
void push(int);
void pop();
void display();
void main()
{
    int c,item;
    do
    {
        printf("Press 1:Push\nPress 2:Pop\nPress 3:Display\nPress 4:Exit\n");
        scanf("%d",&c);
        switch(c)
        {
            case 1:printf("Enter Element\n");
                    scanf("%d",&item);
                    push(item);
                    break;
            case 2:pop();
                    break;
            case 3:display();
                    break;
            case 4:exit(0);
        }
    }while(1);
}
void push(int item)
{
    if(top==Max-1)
    printf("\nStack is Full");
    else
    {
        top++;
        a[top]=item;
    }
}
void pop()
{
    if(top==-1)
    printf("\nStack is Empty");
    else
    {
        printf("\nDeleted Element %d",a[top]);
        top--;
    }
}
void display()
{
    int i;
    printf("Stack : ");
    for(i=top;i>=0;i--)
    printf("%d ",a[i]);
    printf("\n");
}

,Thanks
Bikki Mahato

 

No comments:

Post a Comment