Created
April 27, 2019 15:05
-
-
Save gopherwiz/fb7b72c5b58c9d448d3157e62bbfca8a to your computer and use it in GitHub Desktop.
Revisions
-
gopherwiz created this gist
Apr 27, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,121 @@ // 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; }