Back to all lessons


Lesson 15

Stack

Task 0

Open the stack visualization tool.

Understand how a stack works and how we can manipulate it using pop and push.

Task 1

Create own class IntegerStack. Create fields to store an information about: data and index. Make sure that fields:

  1. are private
  2. are initializabled only by constructor

Assume we can set a maximum height of stack in a constructor parameter.

Task 2

Create three methods:

  1. push - inserts a new element
  2. pop - removes an element from the stack
  3. print - prints all elements from the stack to a console
Task 3

Copy a code snippet written below into a main method and test your stack:


IntegerStack stack = new IntegerStack(20);
stack.push(1);
stack.push(2);
stack.push(3);
stack.print();

stack.pop();
stack.push(4);
stack.push(5);
    
Task 4

There is a term called "boundary conditions". It relates to a definition (in this case to methods) of boundary values.

Copy snippets (separatly) and test your code.


// Case 0
IntegerStack stack = new IntegerStack(20);
stack.pop();

// Case 1
IntegerStack stack = new IntegerStack(1);
stack.push(4);
stack.push(5);

        
Task 5

Make your stack stable (it means: there will be no error with the boundary conditions).

Task 6

Create a class SortingStack. It contains an object of IntegerStack as a field.

SortingStack should have method: addAndSort(int), which pushes a number in proper order.

Create also a method print, which calls printing of the IntegerStack's object.

Task 7

Create a program, that checks if all braces in a file are closed correctly.


Example Result
{} correct
{[ ]} correct
{[}] incorrect
{})( incorrect
[[{({})}]] correct
{}} incorrect