Play and learn 300 000+ tabs online

Saturday, May 29, 2010

STACKS Program solution

Stacks are commonly used Data Structures while writing code. It's concept is
really simple which makes it even simpler to write it in code. Consider this
situation. There are a pile of 5 Books on a Table. You want to add one book to
the pile. What do you do??? You simply add the book on the TOP of the pile. What
if you want the third book from the new 6 book pile? You then lift each book one
by one from the TOP until the third book reaches the top. Then you take the
third book and replace all the others back into the pile by adding them from the
If you've noticed I've mentioned the word TOP in Caps. Yes, TOP is the most
important word as far as stacks are concerned. Data is stored in a Stack where
adding of data is permitted only from the top. Removing/Deleting Data is also
done from the top. As Simple as That. Now you may ask where Stacks are used?
Stacks are infact used on every Processor. Each processor has a stack where data
and addresses are pushed or added to the stack. Again the TOP rule is followed
here. The ESP Register adds as a Stack Pointer that refers to the top of the
stack in the Processor. Anyway, since the explaination of how the Processor
Stack works is beyond the subject of this Tutorial, let's write our Stack Data
Structure. Remember some Stack Terminology before continuing. Adding Data to the
Stack is known as Pushing and deleting data from the stack is known as Popping.

#include <iostream.h>
#include <conio.h>

#define MAX 10        // MAXIMUM STACK CONTENT

class stack

    int arr[MAX];   // Contains all the Data
    int top;        //Contains location of Topmost Data pushed onto Stack

     stack()         //Constructor
        top=-1;      //Sets the Top Location to -1 indicating an empty stack

     void push(int a)  // Push ie. Add Value Function
        top++;        // increment to by 1
            arr[top]=a;  //If Stack is Vacant store Value in Array
            cout<<"STACK FULL!!"<<endl;

    int pop()                  // Delete Item. Returns the deleted item
            cout<<"STACK IS EMPTY!!!"<<endl;
            return NULL;
            int data=arr[top];     //Set Topmost Value in data
            arr[top]=NULL;       //Set Original Location to NULL
            top--;               // Decrement top by 1
            return data;         // Return deleted item

void main()
 stack a;
 cout<<"3 is Pushed\n";
 cout<<"10 is Pushed\n";
 cout<<"1 is Pushed\n\n";

 cout<<a.pop()<<" is Popped\n";
 cout<<a.pop()<<" is Popped\n";
 cout<<a.pop()<<" is Popped\n";

3 is Pushed
10 is Pushed
1 is Pushed

1 is Popped
10 is Popped
3 is Popped

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.