Skip to content

Instantly share code, notes, and snippets.

@canavci2016
Last active September 16, 2022 15:05
Show Gist options
  • Save canavci2016/3b73178ba1106cd07ae036ceab6a00bc to your computer and use it in GitHub Desktop.
Save canavci2016/3b73178ba1106cd07ae036ceab6a00bc to your computer and use it in GitHub Desktop.
stack implementation (fifo) . data elements are retrieved from last to first
#include <iostream>
#include <stack>
template <class T>
class Node
{
private:
T data;
Node *prev;
public:
Node(T data) : data(data), prev(NULL) {}
friend class BuiltinInStack;
};
class BuiltinInStack
{
private:
Node<int> *last;
public:
BuiltinInStack() : last(NULL) {}
BuiltinInStack &push(int value);
int top();
void pop();
bool empty() const;
void loopThrough() const;
};
BuiltinInStack &BuiltinInStack::push(int value)
{
Node<int> *node = new Node<int>(value);
if (empty())
{
last = node;
return *this;
}
node->prev = last;
last = node;
return *this;
}
void BuiltinInStack::loopThrough() const
{
if (empty())
return;
Node<int> *tmp = last;
while (1)
{
std::cout << tmp->data << std::endl;
if (tmp->prev == NULL)
return;
tmp = tmp->prev;
}
}
int BuiltinInStack::top()
{
return !empty() ? last->data : -1;
}
void BuiltinInStack::pop()
{
if (empty())
return;
Node<int> *tmp = (last->prev != NULL) ? last->prev : NULL;
delete last;
last = tmp;
}
bool BuiltinInStack::empty() const { return last == NULL; }
int main(int argc, char *argv[])
{
BuiltinInStack stackBuilt;
for (size_t i = 0; i < 23; i++)
stackBuilt.push(i);
while (!stackBuilt.empty())
{
std::cout << "top is " << stackBuilt.top() << std::endl;
stackBuilt.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment