Advertisement
fellipeh

Untitled

Jun 1st, 2020
1,598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Pilha {
  6. private:
  7.     int pilha[10];
  8.     int ult;
  9. public:
  10.     Pilha();  // construtor
  11.     bool push(int valor);  // inserir
  12.     int pop(); // remover
  13.     int top(); // retorna o ultimo item da pilha
  14.     void print();
  15. };
  16.  
  17. Pilha::Pilha(){
  18.     for (int i=0; i<10; i++){
  19.         pilha[i] = NULL;
  20.     }
  21.  
  22.     ult = -1;
  23. }
  24.  
  25. int Pilha::top(){
  26.     return pilha[ult];
  27. }
  28.  
  29. void Pilha::print(){
  30.     for (int i=0; i <= ult; i++){
  31.         cout << pilha[i] << "  ";
  32.     }
  33.     cout << "\n";
  34. }
  35.  
  36. bool Pilha::push(int valor){
  37.     if (ult == 10)   // verificando se a pilha esta cheia
  38.         return false;
  39.  
  40.     ult++;
  41.     pilha[ult] = valor;
  42.     return true;
  43. }
  44.  
  45. int Pilha::pop(){
  46.     if (ult == -1)  // pilha esta vazia
  47.         return -1;
  48.  
  49.     int vlr_removido = pilha[ult];
  50.  
  51.     pilha[ult] = NULL;
  52.     ult--;
  53.     return vlr_removido;
  54. }
  55.  
  56. int main()
  57. {
  58.     Pilha p;
  59.  
  60.     p.push(9);
  61.     p.push(8);
  62.     p.push(7);
  63.     p.push(6);
  64.     p.push(5);
  65.     p.print();
  66.     p.push(4);
  67.     p.push(3);
  68.     p.push(2);
  69.     p.push(1);
  70.     p.print();
  71.  
  72.     cout << "\nValor removido da pilha: " << p.pop() << "\n";
  73.  
  74.     p.print();
  75.  
  76.     cout << "\nUltimo valor da pilha: " << p.top();
  77.  
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement