1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
/****************************************************************************************** ******************************************************************************************* Chapter 3 Stack and Queue A simple class of Stack! By: Hamed Kiani (Sep. 1, 2015) ****************************************************************************************** ******************************************************************************************/ #include "stdafx.h" #include <iostream> using namespace std; struct Node{ int _data; Node* _next; }; class myStack{ private: Node* _head; int _size; public: myStack(); ~myStack(); void push(int data); void pop(); Node* return_top(); int get_size(); bool is_empty(); void clear(); void print_stack(); }; // constructor myStack::myStack() { _head = NULL; _size = 0; } myStack::~myStack() { clear(); } // is empty function bool myStack::is_empty() { return (_size == 0); } // retrun the stack size int myStack::get_size() { return _size; } // puch on the top void myStack::push(int data) { Node* temp = new Node; temp->_data = data; temp->_next = _head; _head = temp; _size++; } // pop the top data void myStack::pop() { if (is_empty()) { cout << " the stack is empty, poping faild" << endl; return; } Node* temp = _head; _head = _head->_next; delete temp; _size--; } // return the pointer of the top value Node* myStack::return_top() { if (is_empty()) return NULL; Node* temp = _head; return temp; } // empty the stack void myStack::clear() { while(_size) pop(); cout << " stack is deleted" << endl; } // print the stack values void myStack::print_stack() { Node* temp = _head; while(temp != NULL){ cout << temp->_data << " " ; temp = temp->_next; } cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { myStack stack; stack.push(1); stack.push(2); stack.push(3); stack.print_stack(); cout << stack.get_size() << endl; stack.pop(); stack.print_stack(); Node* temp = stack.return_top(); cout << temp->_data << endl; return 0; } |
2 Comments
|
A place to practice the coding interview.
AuthorHamed Kiani Categories
All
Archives |