Stacks:
•A stack is a list of elements in which an element may be inserted
or deleted only at one end, called the TOP of the Stack.
•Stack is a LIFO (Last In First Out) data structure.
•Elements are removed from a stack in the reverse order of that in
which they were inserted into the stack.
Examples
•Stack of Dishes
•Stack of Books
•A packet of Biscuits etc.
•Note: AVAIL List is also implemented using STACK.
STACK
Array Representation of Stacks
Algorithms for push and pop
PUSH (STACK, TOP, MAXSTK, ITEM)
1.[Stack already filled?]
If TOP =MAXSTK, then: Print: OVERFLOW and Return.
2.Set TOP = TOP +1. [Increase TOP by 1.]
3.Set STACK [TOP] = ITEM. [Insert ITEM into the TOP.]
4.Return
POP (STACK, TOP, ITEM)
1.[Stack has an ITEM to be removed?]
If TOP = 0, then: Print: UNDERFLOW and Return.
2.Set ITEM = STACK [TOP]. [ITEM is the TOP
element.]
3.Set TOP = TOP - 1. [Decrease TOP. by 1.]
4.Return
code to implement stack using array
#include<iostream>
using namespace std;
struct arraystack{
int top;
int capacity;
int *array;
};
arraystack* createarray(int cap)
{
arraystack *temp=new arraystack;
temp->capacity=cap;
int *stack=new int[cap];
temp->array=stack;
temp->top=-1;
return temp;
}
int isfull(arraystack *ptr)
{
if(ptr->top==ptr->capacity-1)
{
return 1;
}
else
{
return 0;
}
}
int isempty(arraystack *ptr)
{
if(ptr->top==-1)
{
return 1;
}
else
{
return 0;
}
}
void push(arraystack *ptr,int n)
{
if(!isfull(ptr))
{
ptr->top++;
ptr->array[ptr->top]=n;
}
else
{
cout<<"stack is full";
}
}
int pop(arraystack *ptr)
{
int item;
if(!isempty(ptr))
{
item=ptr->array[ptr->top];
ptr->top--;
return item;
}
else
{
return -1;
}
}
int main()
{
arraystack *stack;
int n,choice,item;
cout<<"enter the capacity of stack\n";
cin>>n;
stack=createarray(n);
while(1)
{
cout<<"\n1. PUSH";
cout<<"\n2. POP";
cout<<"\n3. EXIT";
cout<<"\nENter Your Choice";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter a number to be pushed";
cin>>item;
push(stack,item);
break;
case 2:
item=pop(stack);
if(item==-1)
{
cout<<"stack is empty";
}
else
{
cout<<"poped value is"<<item;
}
break;
case 3:
exit(0);
}
}
return 0;
}
0 Comments