All about C plus plus algorithms!

Saturday 22 July 2017

Stack Class in C++ || Your Own Stack

What is a Stack?

Stack is a static memory in the life cycle of a program. This memory region stores variables and references (pointers). The main feature to consider here is that stack memory works in LIFO order, that is, Last In First Out. So basically it has two functions of Push (pushing elements into the stack) and Pop (Pop out the last element in the stack). Also there is another function Top which lets you know which element is placed on the last filled slot. 

My own Stack Class

This class will have functions as Push, Pop, Top as well as some other utility functions like GetAt(int index) which tell that what element is placed on the index. And other functions like Size( ), Print( ) Empty( ) and Invert( ). 

To make this class, I have used Vector class that I made. To see it's code and explanation please view Vector Class and Iterator for it

template <typename T>
class myStack
{
Vector <T> st;

public:

       //utility functions and constructors here

}


This class is has small and easy code, which I believe needs no explaining. So I'll just share the code. 

#pragma once

#pragma once
#include <iostream>
#include "vector.h"
using namespace std;

template <typename T>
class myStack
{
Vector <T> st;

public:

void push(const T & obj)
{
st.push_back(obj);
}

void pop()
{
st.pop_back();
}

T top()
{
int s = st.getSize() - 1;
T ret = st[s];
return ret;
}

int size()
{
return st.getSize();
}

bool empty()     //returns true if stack is empty
{
if (st.getSize()== 0)
return true;

return false;
}

void invert()
{
int i = 0;
int s = st.getSize();
Vector <T> temp;
for (i = s-1; i >= 0; i--)
{
temp.push_back(st[i]);
}
st = temp;
}

T getAt(int i)
{
return st[i];
}

void print()
{
for (int j = 0; j < st.getSize(); j++)
{
cout << st[j];
}
}

};

Links for Code files





Thank you for reading. ^^
Share:

0 comments:

Post a Comment

Popular Posts

Blog Archive

Copyright by progrithms.blogspot.com. All Rights Reserved.. Powered by Blogger.

Copyright © Programs and Algorithms | Powered by Blogger

Design by ThemePacific | Blogger Theme by NewBloggerThemes.com