Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1.  
  2.  
  3.  
  4. #pragma once
  5. struct node
  6. {
  7.     int value;
  8.     node* previous;
  9.  
  10.     node(int value, node* previous)
  11.     {
  12.         this->value = value;
  13.         this->previous = previous;
  14.     }
  15. };
  16. class Stack
  17. {
  18. private:
  19.     node* top = nullptr;
  20.  
  21. public:
  22.     void push(int value);
  23.  
  24.     void pop();
  25.  
  26.     int peek()const;
  27.  
  28.     void print();
  29.  
  30.     bool isEmpty()const;
  31.  
  32.     Stack();
  33.     Stack(const Stack& s);
  34.  
  35.     ~Stack();
  36. };
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48. #include "Stack.h"
  49. #include <iostream>
  50.  
  51. void Stack::push(int value)
  52. {
  53.     if (top == nullptr)
  54.     {
  55.         top = new node(value, nullptr);
  56.     }
  57.     else
  58.     {
  59.         node* newNode = new node(value, top);
  60.         top = newNode;
  61.     }
  62. }
  63.  
  64. void Stack::pop()
  65. {
  66.     if (!isEmpty())
  67.     {
  68.         node* temp = top->previous;
  69.         delete top;
  70.         top = temp;
  71.     }
  72. }
  73.  
  74. int Stack::peek() const
  75. {
  76.     if (!isEmpty())
  77.     {
  78.         return top->value;
  79.     }
  80.     // TODO: insert return statement here
  81. }
  82.  
  83. void Stack::print()
  84. {
  85.     if (!isEmpty())
  86.     {
  87.         node* temp = top;
  88.         while (temp != nullptr)
  89.         {
  90.             std::cout << temp->value << std::endl;
  91.             temp = temp->previous;
  92.         }
  93.     }
  94.     else
  95.     {
  96.         std::cout << "Stack is empty." << std::endl;
  97.     }
  98.    
  99.  
  100. }
  101.  
  102. bool Stack::isEmpty()const
  103. {
  104.     if (top == nullptr)return true;
  105.     return false;
  106. }
  107.  
  108. Stack::Stack()
  109. {
  110.     //
  111.     top = nullptr;
  112. }
  113.  
  114. Stack::Stack(const Stack & s)
  115. {
  116. }
  117.  
  118. Stack::~Stack()
  119. {
  120.     while (!isEmpty())pop();
  121. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement