[cpp] Stack
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- #include <iostream>
- const int MAX_SIZE = 10;
- class Stack
- {
- public:
- Stack()
- {
- size = MAX_SIZE;
- items = new int[ size ];
- top_index = -1;
- }
- ~Stack()
- {
- delete[] items;
- }
- void push( int value )
- {
- if( !full() )
- {
- ++top_index;
- items[ top_index ] = value;
- }
- else
- {
- std::cerr << "Stos pełny!" << std::endl;
- }
- }
- int pop()
- {
- if( !empty() )
- {
- int popped = items[ top_index ];
- --top_index;
- return popped;
- }
- else
- {
- std::cerr << "Stos pusty!" << std::endl;
- return -1;
- }
- }
- int top()
- {
- if( !empty() )
- {
- return items[ top_index ];
- }
- else
- {
- std::cerr << "Stos pusty!" << std::endl;
- return -1;
- }
- }
- bool empty() const
- {
- return top_index == -1;
- }
- bool full() const
- {
- return top_index == size - 1;
- }
- void destroy()
- {
- top_index = -1;
- }
- private:
- int* items;
- int top_index;
- int size;
- };
- int main()
- {
- Stack stack1;
- Stack stack2;
- std::cout << "Wczytaj 10 liczb do stosu: " << std::endl;
- for( int i = 0; i < 10; ++i )
- {
- int num;
- std::cin >> num;
- stack1.push( num );
- }
- std::cout << "Liczby ze stosu 1: " << std::endl;
- while( !stack1.empty() )
- {
- int num = stack1.pop();
- std::cout << num << std::endl;
- stack2.push( num );
- }
- std::cout << "Liczby ze stosu 1 po wypisaniu: " << std::endl;
- while( !stack2.empty() )
- {
- int num = stack2.pop();
- std::cout << num << std::endl;
- }
- return 0;
- }
Editor
You can edit this paste and save as new:
File Description
- Stack
- Paste Code
- 29 Mar-2024
- 1.9 Kb
You can Share it: