Implementation of Stack

Implement Stack using LL

struct StackNode
{
    int data;
    StackNode *next;
    StackNode(int a)
    {
        data = a;
        next = NULL;
    }
};

struct MyStack
{
    StackNode *top;

    void push(int);
    int pop();
    MyStack() { top = NULL; }
};



//Function to push an integer into the stack.
void MyStack ::push(int x)
{
    // Your Code
    StackNode *p = new StackNode(x);

    if (!top)
    {
        top = p;
    }
    else
    {
        StackNode *temp = NULL;
        temp = top;
        top = p;
        p->next = temp;
    }
}

// Function to remove an item from top of the stack.
int MyStack ::pop()
{
    // Your Code

    if (!top)
    {
        return -1;
    }

    int x = top->data;

    top = top->next;

    return x;
}

Last updated