Stacks


Stacks are data structures which are quite useful. A stack is similar to the stacks you have come across. It is a first in last out (FILO) data structure.

There are two main operations in stacks: A pop operation which removes the topmost element to the stack and the push operation which adds an element to the stack.

Elements are removed from the stack in reverse order, i.e., the elements which are inserted first are removed last.

Applications of stacks are:

  1. Solving “Tower Of Hanoi” problem
  2. Evaluation of Prefix and Postfix expressions
    Postfix expressions are those in which the operand is written after the operators.
    Eg:-  a+b=>ab+
    Prefix expression are the opposite
    Eg:- a+b=>+ab
  3. It is also used in backtracking. Backtracking is an algorithm which is used to store the results so they can be evaluated again if required

Now, lets define the stack. It will have only two operations, Push and Pop. Push will add an element to the stack while Pop will remove an element from the stack.

Now, we will define a stack in C++:


#include<iostream.h>

using namespace std;

class Stack
{
private:
int elements[100]={0};
int top;
public:
int num;
stack()
{
top=-1;
}

void push(int num)
{
top++;
if(top<100)
{
elements[top]=num;
cout<<"Element Added"<<endl;
}
else
{
cout<<"Stack is full"<<endl;
}
}

 void pop()
 {

 if(top<-1)
 {
 top++
 cout<<"Stack is empty"<<endl;
 }
 else
 {
 num=element[top];
 cout<<"Element number "<<top+1<<"is"<<num<<endl;
 element[top]=o;
 }
}

int main()
{
 Stack stack;
 stack.push(8);
 stack.push(12);
 stack.pop();
}
/*------------------OUTPUT---------------------*/
/*Element number 2 is 12*/

The code is self explanatory, if you don’t get it, please feel free to comment or to mail me.

In the next post, we shall see the application of stacks in problems like Tower of hanoi or an infix to postfix conversion

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s