Implement Stack using Linked List

PHOTO EMBED

Sat Dec 02 2023 18:17:00 GMT+0000 (Coordinated Universal Time)

Saved by @nistha_jnn #c++

#include <bits/stdc++.h>
using namespace std;

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

class MyStack {
  private:
    StackNode *top;

  public:
    void push(int);
    int pop();
    MyStack() { top = NULL; }
};
//Function to push an integer into the stack.
void MyStack ::push(int x) 
{
   StackNode* newnode=new StackNode(x);
   newnode->next=top;
   top=newnode;
  
}

//Function to remove an item from top of the stack.
int MyStack ::pop() 
{
    int ddata;
    if(top==NULL)
    {
        return -1;
    }
     ddata=top->data;
    top=top->next;
    return ddata;
}

content_copyCOPY

🟥⬇️🟥⬇️🟥⬇️ first square-new node and down arrow represent next pointer and we have to connect node with rest of stack using down that is top pointer