Stack implementation in C++
Here is the code : Debug, Run and Learn
Thanks
#include <iostream> #include <conio.h> using namespace std; struct node { int val; node *next; node(int value) { val = value; next = NULL; } }; class stack { private: node *head; public: stack() : head(NULL) {} void push(int val) { if (head == NULL) { head = new node(val); } else { node *newNode = new node(val); newNode->next = head; head = newNode; } } int top() { return head->val; } void pop() { node *nextNode = head->next; delete head; head = nextNode; } void printStack() { cout << endl << "Stack Traces : "; for (node *current = head; current != NULL; current = current->next) { cout << current->val << " "; } } ~stack() { while (head != NULL) { pop(); } } }; void main() { { stack myStack; for (int index = 1; index <= 10; ++index) { myStack.push(index); } myStack.printStack(); } _getch(); }
Thanks
Comments
Post a Comment