Skip to content

Instantly share code, notes, and snippets.

@web3dev6
Created April 27, 2019 15:05
Show Gist options
  • Save web3dev6/fb7b72c5b58c9d448d3157e62bbfca8a to your computer and use it in GitHub Desktop.
Save web3dev6/fb7b72c5b58c9d448d3157e62bbfca8a to your computer and use it in GitHub Desktop.
An object oriented implementation of stack using arrays in C++
// Stack - Object oriented implementation using linked lists
#include <iostream>
using namespace std;
class Node
{
public:
Node* next;
int data;
};
class Stack
{
public:
Node* head; // pointer to the first node of stack
int length; // variable to mark the length of stack
Stack();
~Stack();
void push(int x);
void pop();
int displayTop();
int isEmpty();
void print();
};
// Constructor
Stack::Stack(){
this->head = NULL;
this->length = 0;
}
//Destructor
Stack::~Stack(){
std::cout << "LIST DELETED\n";
}
// Push operation to insert an element on top of stack.
void Stack::push(int x){
Node* newNode = new Node();
newNode->data = x;
newNode->next = this->head;
this->head = newNode;
this->length++;
return;
}
// Pop operation to remove an element from top of stack.
void Stack::pop(){
if(head == NULL)
printf("Error: No element to pop\n");
Node* temp = this->head;
this->head = head->next;
free(temp);
return;
}
// Top operation to return element at top of stack.
int Stack::displayTop(){
if(head == NULL){
printf("Empty Stack!\n");
return 0;
}
return (this->head->data);
}
// This function will return 1 (true) if stack is empty, 0 (false) otherwise
int Stack::isEmpty(){
if(head == NULL)
return 1;
return 0;
}
// This will print all the elements in the stack at any stage.
void Stack::print(){
printf("Stack: ");
Node* temp = this->head;
while(temp != NULL){
if(temp->next == NULL){
printf("%d\n", temp->data);
return;
}
printf("%d->", temp->data);
temp = temp->next;
}
return;
}
int main()
{
// Code to test the implementation.
// calling Print() after each push or pop to see the state of stack.
Stack S;
S.push(2);S.print();
S.push(5);S.print();
S.push(10);S.print();
S.pop();S.print();
S.push(12);S.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment