diff options
| author | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
|---|---|---|
| committer | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
| commit | 33613a85afc4b1481367fbe92a17ee59c240250b (patch) | |
| tree | 670b842326116b376b505ec2263878912fca97e2 /Bachelor/Prog2/Stack/Tstack1.h | |
| download | Studium-33613a85afc4b1481367fbe92a17ee59c240250b.tar.gz Studium-33613a85afc4b1481367fbe92a17ee59c240250b.tar.bz2 | |
Diffstat (limited to 'Bachelor/Prog2/Stack/Tstack1.h')
| -rw-r--r-- | Bachelor/Prog2/Stack/Tstack1.h | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/Bachelor/Prog2/Stack/Tstack1.h b/Bachelor/Prog2/Stack/Tstack1.h new file mode 100644 index 0000000..8cbc5d5 --- /dev/null +++ b/Bachelor/Prog2/Stack/Tstack1.h @@ -0,0 +1,53 @@ +// tstack1.h
+// Class template Stack
+
+#ifndef TSTACK1_H
+#define TSTACK1_H
+
+template< class T, int elements > // # of elements in the stack
+class Stack {
+public:
+ Stack(); // default constructor
+ // ~Stack() { delete [] stackPtr; } // destructor (only for dynamic version)
+ bool push( const T& ); // push an element onto the stack
+ bool pop( T& ); // pop an element off the stack
+private:
+ int top; // location of the top element
+ T stackHolder[elements]; // static array for stack
+ // T *stackPtr; // pointer to the stack (only for dynamic version)
+ bool isEmpty() const { return top == -1; } // utility
+ bool isFull() const { return top == elements - 1; } // functions
+};
+
+// Constructor with default size 10
+template< class T, int elements >
+Stack< T, elements>::Stack()
+{
+ top = -1; // Stack is initially empty
+ // stackPtr = new T[ elements ]; // dynamically allocate space for elements (not used)
+}
+
+// Push an element onto the stack
+// return 1 if successful, 0 otherwise
+template< class T, int elements >
+bool Stack< T, elements >::push( const T &pushValue )
+{
+ if ( !isFull() ) {
+ stackHolder[ ++top ] = pushValue; // place item in Stack
+ return true; // push successful
+ }
+ return false; // push unsuccessful
+}
+
+// Pop an element off the stack
+template< class T, int elements >
+bool Stack< T, elements >::pop( T &popValue )
+{
+ if ( !isEmpty() ) {
+ popValue = stackHolder[ top-- ]; // remove item from Stack
+ return true; // pop successful
+ }
+ return false; // pop unsuccessful
+}
+
+#endif
\ No newline at end of file |
