Stack in C++ Using a Recursive Method   Leave a comment

// Stack in C++ Using a Recursive Method
//
// Created by ED on 2013-04-14

#include <iostream>
using namespace std;

// header

#ifndef STACK_H
#define STACK_H

template <typename T>
class Stack;

template <typename T>
class Node {
    T _data;
    Node<T>* _next;
    Node(T data, Node<T>* next = (Node<T>*) 0);
    friend class Stack<T>;
};

template <typename T>
class Stack {
    Node<T>* _cur;
    Node<T>* _top;
public:
    Stack();
    int dept(unsigned int cnt = 0);
    bool isEmpty() const;
    T pop();
    void push(T data);
    virtual ~Stack();
};

#endif

// methods

template <typename T>
Node<T>::Node(T data, Node<T>* next) :
_data(data), _next(next) {
}

template <typename T>
Stack<T>::Stack() {
    _top = (Node<T>*) 0;
}

// recursive method
template <typename T>
int Stack<T>::dept(unsigned int cnt) {
    if (cnt == 0)
        _cur = _top;
    if (!_cur)
        return cnt;
    else {
        _cur = _cur->_next;
        return dept(cnt + 1);
    }
}

template <typename T>
bool Stack<T>::isEmpty() const {
    return !_top;
}

template <typename T>
T Stack<T>::pop() {
    T topData = _top->_data;
    Node<T>* toDel = _top;
    _top = _top->_next;
    delete toDel;
    return topData;
}

template <typename T>
void Stack<T>::push(T data) {
    Node<T>* newNode = new Node<T>(data, _top);
    _top = newNode;
}

template <typename T>
Stack<T>::~Stack() {
    while (!isEmpty()) {
        pop();
    }
}

// main

int main() {
    Stack<double> S;
    S.push(1.2345);
    S.push(2.3456);
    S.push(3.4567);
    cout << S.dept() << endl;
    cout << S.pop() << endl;
    cout << S.dept() << endl;
    cout << (S.isEmpty() ? "true" : "false") << endl;
    cout << S.pop() << endl;
    cout << S.pop() << endl;
    cout << S.dept() << endl;
    cout << (S.isEmpty() ? "true" : "false") << endl;
    return 0;
}

Posted 2013/04/14 by oop344ed in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: