Monday, June 24, 2013

Stacks and C++ Program | Data Structures And Algorithms

Stacks is a Data Structure in computer and a Abstract Data Type. Abstract Data Types (ADT's) is defined as a mathematical model of the data objects that make up a data type as well as the functions that operate on these objects.

Example: Int type defining a variable a and b and then adding
You would get the same result as you would by adding two numbers mathematically

Stacks is a container of objects that are inserted and removed using Last-in-first-out principle. Objects can be inserted at any time, but only the last (the most-recently added) object can be removed.

Pushing: Inseting an item.
Popping: removing an item.

Stacks are supported with the following methods Four Main Methods.
1) new(): ADT - creates a new stack
2) push(S:ADT, o:element): - Inserts object o onto top of stack S
3) pop(S:ADT): ADt - removes the top object of stack S, error if stack is empty
4) top(S:ADT): Element - returns the top object of stack without removing it,
             error if stack is empty.

Other Methods
1) Size(S:ADT):Integer - returns num of objects in stack S
2) isEmpty(S:ADT):Boolean - Indicates if stack is empty

Axioms that defines the methods:
Pop (Push(S,v)) = S
Top(Push(S,v)) = v

Stack in C++ Program
#include <iostream>
using namespace std;

const int MAX_STK_SIZE = 100;

class stack
{
private:
    int stk[MAX_STK_SIZE];
    int top;

public:
    stack()    { top = -1; }

    void push (int x)
    {
        if (top > 10)
            cout << "The stack is Full";
        stk[++top] = x;
        cout << "Successfully Inserted" << x <<endl;
    }

    void pop()
    {
        if (top < 0)
            cout << "Stack is empty";
        cout<<"The Deleted element is: "<< stk[top--] <<endl;
    }

    void display()
    {
        if (top < 0)
            cout << "Stack is empty";

        for (int i = top; i >=0; i--)
            cout <<stk[i] <<" ";
    }
};

int main ()
{
    int ch;
    stack st;
    while (true)
    {
        cout <<endl <<"Press 1 to push "<<endl <<"Press 2 to pop";
        cout <<endl <<"Press 3 to Display" <<endl <<"Press 4 to exit" <<endl;
        cin >>ch;
        switch (ch)
        {
        case 1:
            cout<<"Enter the element: ";
            cin >>ch;
            st.push(ch);
            break;
        case 2:
            st.pop();
            break;
        case 3:
            st.display();
            break;
        case 4:
            exit(0);
        }
    }
    system("pause");
    return 0;
}

No comments:

Post a Comment