Implement stack data structure and its operations using singly linked lists.


Implement stack data structure and its operations using singly linked lists.



 #include <iostream>

using namespace std;


class Node {

public:

    int data;    // Data stored in the node

    Node* next;  // Pointer to the next node


    // Constructor

    Node(int value) {

        data = value;

        next = nullptr;

    }

};


class Stack {

private:

    Node* top;  // Pointer to the top node of the stack


public:

    // Constructor

    Stack() {

        top = nullptr;

    }


    bool isEmpty() {

        return (top == nullptr);

    }


    void push(int value) {

        Node* newNode = new Node(value);

        newNode->next = top;

        top = newNode;

        cout << "Pushed element: " << value << endl;

    }


    void pop() {

        if (isEmpty()) {

            cout << "Stack Underflow: Cannot pop element. Stack is empty." << endl;

            return;

        }


        Node* temp = top;

        int poppedElement = top->data;

        top = top->next;

        delete temp;

        cout << "Popped element: " << poppedElement << endl;

    }


    int peek() {

        if (isEmpty()) {

            cout << "Stack is empty." << endl;

            return -1;

        }


        return top->data;

    }


    void display() {

        if (isEmpty()) {

            cout << "Stack is empty." << endl;

            return;

        }


        cout << "Stack elements: ";

        Node* current = top;

        while (current != nullptr) {

            cout << current->data << " ";

            current = current->next;

        }

        cout << endl;

    }

};


int main() {

    Stack stack;


    stack.push(1);

    stack.push(2);

    stack.push(3);

    stack.display();


    cout << "Top element: " << stack.peek() << endl;


    stack.pop();

    stack.display();


    stack.pop();

    stack.pop();


    stack.display();


    return 0;

}


Comments

Popular posts from this blog

Load a Pandas dataframe with a selected dataset. Identify and count the missing values in a dataframe. Clean the data after removing noise as follows: a. Drop duplicate rows. b. Detect the outliers and remove the rows having outliers c. Identify the most correlated positively correlated attributes and negatively correlated attributes

The weights of 8 boys in kilograms: 45, 39, 53, 45, 43, 48, 50, 45. Find the median

Download any dataset and do the following: a. Count number of categorical and numeric features b. Remove one correlated attribute (if any) c. Display five-number summary of each attribute and show it visually