Exam 2 - Question 1 (b)

 avatar
itsLu
c_cpp
a year ago
1.4 kB
7
Indexable
#include <iostream>
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 get_length()
    {
        int counter = 0;
        node * temp;
        for(temp = top ; temp != NULL ; temp = temp->next)
            counter++;
        return counter;
    }
    void searchInStack(int key)
    {
        node * temp;
        bool isFound = false;
        for(temp = top ; temp != NULL ; temp = temp->next)
        {
            if(temp->data == key)
            {
                isFound = true;
                break;
            }
        }
        if(isFound == true)
            cout << "\nNumber is in the stack\n";
        else
            cout << "\nNumber is not in stack\n";
    }
};
Editor is loading...
Leave a Comment