Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2014
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. #include "Stack.h"
  2.  
  3. Stack::Stack(int size){ // constructor
  4. cout << "Constructing a stack...\n";
  5. stack = new int[size];
  6. top = 0;
  7. maxsize = size - 1;
  8. }
  9. Stack::Stack(const Stack &oldStack){ // copy constructor
  10. cout << "Copying the stack...\n";
  11. stack = new int[oldStack.capacity()];
  12. top = oldStack.top;
  13. maxsize = oldStack.maxsize;
  14. stack = oldStack.stack;
  15. }
  16. Stack::~Stack(){ // destructor
  17. delete stack;
  18. delete &top;
  19. delete &maxsize;
  20. }
  21.  
  22. void Stack::push(int val){ // push an int into a Stack
  23. if (top <= maxsize){
  24. cout << "pushing " << val << " to index " << top << "\n";
  25. stack[top] = val;
  26. ++top;
  27. }
  28. else{
  29. cout << "could not push; stack full\n";
  30. }
  31. }
  32. int Stack::pop(){ // pop an int from a Stack
  33. if (top != 0){
  34. //cout << stack[top-1];
  35. int val = stack[top-1]; //the value we're popping from the stack
  36. stack[top-1] = 0;
  37. --top;
  38. return val;
  39. }
  40. else{
  41. cout << "could not pop; stack empty\n";
  42. return -1;
  43. }
  44.  
  45. }
  46.  
  47. bool Stack::empty() const{ // is the Stack empty?
  48. if (top == 0)
  49. return true;
  50. else
  51. return false;
  52. }
  53. bool Stack::full() const{ // is the Stack full?
  54. if (top == maxsize)
  55. return true;
  56. else
  57. return false;
  58. }
  59.  
  60. int Stack::capacity() const{ // capacity of the stack
  61. return maxsize + 1;
  62. }
  63. int Stack::size() const{ // current size of the stack
  64. return top;
  65. }
  66.  
  67. ostream &operator <<(ostream &out, const Stack &currentStack){
  68. //this loop will display each element on its own line.
  69. //each line will be preceded by the index corresponding to the element.
  70. for (int i = currentStack.size() - 1; i >= 0; --i)
  71. {
  72. out << "<" << i << "> " << currentStack.stack[i] << '\n';
  73. }
  74.  
  75. return out;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement