SHAH MD IMRAN HOSSAIN
SHAH MD IMRAN HOSSAIN

Reputation: 2899

Problems in implementing top in my own stack

I am trying implement my own Generic Stack

there is some problem implementing Top Function, which returns the last element of the stack

But when head == NULL there's nothing left to return

#include <iostream>
#include <string>
using namespace std;

template <class anyType>
class Stack
{
    private: struct node
    {
        anyType data;
        node* nextAddress;
    };

    private: node* head;

    public: Stack()
    {
        head = NULL;
    }

    public: anyType Top()
    {
        if (head == NULL)
        {
            cout<<"Stack is empty"<<endl;

            return NULL;
        }

        node* travel = head;

        while(travel -> nextAddress != NULL)
        {
            travel = travel -> nextAddress;
        }

        return travel -> data;
    }

};


struct Student
{
    int id;
    string name;
};

int main(int argc, char const *argv[])
{
    Stack <Student> obj;

    return 0;
}

So, when I return NULL then it's give problem because NULL != anyType

Can anyone help me how can I solve this problem

Upvotes: 1

Views: 67

Answers (1)

paxdiablo
paxdiablo

Reputation: 881783

If your function is defined as returning an actual object (as opposed to a pointer to an object) and you need to indicate that such an object does not exist, the best way to do it is probably just to throw an exception.

In other words, something like:

if (head == nullptr) {
    throw std::runtime_error("stack is empty, no top");
}

Then, in code that calls it, you just need to take that into account:

try {
    processHeadSomehow(stack.Top());
} catch (std::runtime_error &e) {
    std::cout << "No top element, couldn't process\n";
}

In terms of a more usable example, see the code below. It's the basic operations for a general purpose stack, including push, pop, top, clear (and dump for debugging). Note that the code for traversing the list to the end has been removed. That's because we push items on to the start of the linked list so that's where we need to take them off (for pop) or view them (for top).

#include <iostream>
#include <string>
#include <exception>
using std::cout; using std::string; using std::runtime_error;

template <class AnyType> class Stack {
    struct Node { AnyType data; Node *next; };

public:
    Stack() { m_head = nullptr; }

    ~Stack() { Clear(); }

    void Dump() {
        cout << "\n";
        auto curr = m_head;
        auto count = 0;
        while (curr != nullptr) {
            cout << "Item #" << ++count << " is " << curr->data << "\n";
            curr = curr->next;
        }
        cout << "-- Number of items was " << count << "\n";
    }

    void Clear() {
        auto curr = m_head;
        m_head = nullptr;
        while (curr != nullptr) {
            Node *toFree = curr;
            curr = curr->next;
            delete toFree;
        }
    }

    void Push(AnyType item) {
        auto newItem = new Node;
        newItem->data = item;

        if (m_head == nullptr) {
            newItem->next = nullptr;
            m_head = newItem;
        } else {
            newItem->next = m_head;
            m_head = newItem;
        }
    }

    AnyType Pop() {
        if (m_head == nullptr)
            throw runtime_error("Stack empty");

        Node *toFree = m_head;
        m_head = m_head->next;

        AnyType retVal = toFree->data;
        delete toFree;

        return retVal;
    }

    AnyType Top() {
        if (m_head == nullptr)
            throw runtime_error("Stack empty");
        return m_head->data;
    }

private:
    Node *m_head;
};

int main(int argc, char const *argv[])
{
    Stack<string> stack;

    for (const string str: {"", "Pax", "Imran", "Joel"}) {
        if (! str.empty())
            stack.Push(str);
        stack.Dump();
        try {
            cout << "Top of stack is " << stack.Top() << "\n";
        } catch (runtime_error &e) {
            cout << "Exception getting top: " << e.what() << "\n";
        }
    }

    try {
        auto popped = stack.Pop();
        stack.Dump();
        cout << "This is after we popped " << popped << "\n";
        cout << "Top of stack is " << stack.Top() << "\n";
    } catch (runtime_error &e) {
        cout << "Exception getting top: " << e.what() << "\n";
    }

    return 0;
}

When running that with the test main, we see the expected behaviour:

-- Number of items was 0
Exception getting top: Stack empty

Item #1 is Pax
-- Number of items was 1
Top of stack is Pax

Item #1 is Imran
Item #2 is Pax
-- Number of items was 2
Top of stack is Imran

Item #1 is Joel
Item #2 is Imran
Item #3 is Pax
-- Number of items was 3
Top of stack is Joel

Item #1 is Imran
Item #2 is Pax
-- Number of items was 2
This is after we popped Joel
Top of stack is Imran

Upvotes: 7

Related Questions