3. TEMPLATES
‼Short reminder: why do we need templates?
Study ex1.cpp: KeyStorage class from the previous
lab
Pay attention to the way of defining the class
methods
5. STACK
instance of an abstract data type (ADT) that
formalizes the concept of restricted collection (LIFO
= last in first out)
ADT vs. Data Structures: ADT is in the logical level
and data structure is in the implementation level:
ADT: the stack itself
Data Structure: the stack implemented with an array
6. STACK: ACCESS TO ELEMENTS
‼ In a stack, all the operations take
place at the top of the top of the
stack.
Consequently, we can have access
to stack elements only through the
top of the stack.
7. STACK: BASIC OPERATIONS
push(x)
Adds the element x at the top of the stack
pop()
Removes the element from the top of the stack and returns it
Returns an error if the stack is empty
8. STACK: BASIC OPERATIONS
peek()
Returns (but does not remove) the element at the top of the stack
isEmpty()
Returns 1 if the stack is empty and 0 otherwise
9. STACK: ARRAY-BASED IMPLEMENTATION
Study stack_basic.cpp
Test the basic operations for a stack of char elements
Implement the following functionalities:
display all the elements of a stack
sort the elements of the stack
Test the new methods!
10. STACK: APPLICATIONS
‼Exercise: Implement a class named LargeStack which can stock
two arbitrary values of type T (use class templates). The class can
have just two members:
Stack<T> Smain, Saux;
Smain is the main stack which allows stocking the values added to
LargeStack.
Saux is the auxiliary stack which has to be empty before and after the
call to a function of LargeStack class.
LargeStack class has the following main functions:
void push(T x): add an element x to the top of the Smain stack
T pop() : delete and return the element of the top of Smain stack
void swap(int i): exchange the values from level i and j of Smain
stack. The levels are numbered starting with 0. If an error
occurs, the stack won’t be modified. You can use Saux stack for
temporary stocking of any values you want.
11. HOMEWORK
Finish all the lab exercises.
Using a stack, implement an algorithm for converting a
number from a base to another base.
For instance, 510 = 1012 .
Using a stack, check whether a given string is palindrome or
not.