Stack

Vid:

Code:
Array Implementation:

#include<iostream>
using namespace std;
#define MAX_SIZE 101
int A[MAX_SIZE];
int top=-1; //top==index of array
void push(int x){
//top++;
//A[top]=x;
if(top==MAX_SIZE-1){
    cout<<"Stack Overflow";
    return;
}
A[++top]=x; //here pre increment operator is using
}
void pop()
{
    if(top==-1){
        cout<<"No element to return";
        return;
    }
    top--;
}
int Top()
{
    return A[top];
}
void print()
{
    cout<<"Stack:";
    for(int i=0; i<=top; i++){
    cout<<" "<<A[i]<<" ";
    }
 cout<<endl;

}
int main()
{
push(2);print();
push(1);print();
push(7);print();
pop();print();
pop();print();
push(10);print();
}

OOP Implementation with Array:

#include<iostream>
using namespace std;
#define MAX_SIZE 101
class Stack{
private:
int A[MAX_SIZE];
int top; //top==index of array
public:
    Stack(){
        top=-1;
    }
    void push(int x)
    {
        if(top==MAX_SIZE-1){
            cout<<"err: stackoverflow";
            return;
        }
        A[++top]=x;
    }
    void pop()
    {
        if(top==-1)
        {
            cout<<"No element to pop";
            return;
        }
        top--;
    }
    int Top(){
        return A[top];
    }
    int IsEmpty(){
        if(top==-1)
            return 1;
        return 0;
    }
    void print(){
        int i;
        cout<<"Stack: ";
        for(i=0;i<=top;i++){
            cout<<A[i]<<" ";
        }
        cout<<endl;
    }
};

int main(){
    Stack S;
    S.push(2);S.print();
    S.push(5);S.print();
    S.push(10);S.print();
    S.pop();S.print();
    S.pop();S.print();
    S.push(18);S.print();
}

 

Practice Problem:
http://www.mycodeschool.com/problems/stock-market

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *