Exam 5 - Question 1

 avatar
itsLu
c_cpp
2 months ago
1.8 kB
2
Indexable
Never
#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 < 10 ; k++)
    {
        temp = rand() % 20;
        if(temp % 2 == 0)
            evenStack.push(temp);
        else
            oddStack.push(temp);
    }
    evenStack.displayStack();
    cout << "\n";
    oddStack.displayStack();
}
Leave a Comment