Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stack Impl

Snippet info

Language

Cpp

Visibility

public

Author

preeti.gaur1790

Created

2022-05-24T13:41:17.951711Z

Updated

2022-05-28T11:12:59.336911Z

#include <iostream>
using namespace std;

class Node {
  public :
  int data;
  Node *next;
  
  Node() {
      data = 0;
      next = NULL;
  }
  
  Node(int data) {
      this->data = data;
      this->next = NULL;
  }
};

class Stack {
    Node *top;
    
    public : 
    
    void push(int data);
    void pop();
    void peek();
    void display();
    bool isEmpty();
};

bool Stack::isEmpty() {
    if(top == NULL) {
        return true;
    }
    return false;
}

void Stack::push(int data) {
    Node *newNode = new Node(data);
    
    if(top == NULL) {
        top = newNode;
        return;
    }
    
    newNode->next = top;
    top = newNode;
}

void Stack::pop() {
     if(top == NULL) {
         cout << "Stack is Empty" << endl ;
     }
     
     Node *temp = top;
     top= top->next;
     
     cout << "Pop : " << temp->data << endl;
     delete temp;
}

void Stack::peek() {
     if(top == NULL) {
         cout << "Stack is Empty" << endl ;
     }
     
     cout << "Peep : " << top->data << endl;
}    

void Stack::display() {
    if(top == NULL) {
         cout << "Stack is Empty" << endl ;
     }
     
      Node *temp = top;
      while(temp != NULL) {
          cout << temp->data << endl;
          temp = temp->next;
      }
}

int main() {
    
    Stack *stack =  new Stack();
    stack->push(1);
    stack->push(2);
    stack->push(3);
    stack->push(4);
    stack->display();
    stack->pop();
    stack->peek();
    stack->display();
    stack->push(5);
    stack->display();
    return 0;
}
    
    
    
    
    
INFO