Exam 4 - Question 3

 avatar
itsLu
c_cpp
a year ago
1.8 kB
5
Indexable
#include <iostream>
#include <ctime>
using namespace std;

struct node
{
    int data;
    node * next;
};

class linkedStack
{
    node * top;
public:
    linkedStack()
    {
        top = NULL;
    }
    void push(int data)
    {
        node * temp = new node;
        temp->data = data; // (*temp).data = data;
        temp->next = top;
        top = temp;
    }
    bool isEmpty()
    {
        return top == NULL;
    }
    int pop()
    {
        if(isEmpty())
        {
            cout << "Stack is empty\n";
            return -1;
        }
        node * temp = top;
        int tempData = temp->data;
        top = top->next;
        delete temp;
        return tempData;
    }
    int getNumberOfElements()
    {
        int counter = 0;
        node * temp;
        for(temp = top ; temp != NULL ; temp = temp->next)
            counter++;
        return counter;
    }
    void displayStack()
    {
        node * temp;
        for(temp = top ; temp != NULL ; temp = temp->next)
            cout << temp->data << "\t";
    }
    void deleteStack()
    {
        node * temp;
        while(top != NULL)
        {
            temp = top;
            top = top->next;
            delete temp;
        }
    }
    ~linkedStack()
    {
        deleteStack();
        cout << "Stack is deleted\n";
    }
};

int main()
{
    linkedStack oddStack , evenStack;
    int temp;
    srand(time(NULL));
    for(int k = 0 ; k < 100 ; k++)
    {
        temp = rand();
        if(temp % 2 == 0)
            evenStack.push(temp);
        else
            oddStack.push(temp);
    }
    evenStack.displayStack();
    cout << "\n";
    oddStack.displayStack();
}
Editor is loading...
Leave a Comment