[Data Structure] Stack with JAVA

Seonggil Jeong
2 min readJul 14, 2022

--

Stack

In a Last In First Out (LIFO) stack, data can always be inserted or removed from only one side, the end of the list.

I will explain the features of the stack and how to implement it in Java

What is Stack?

As mentioned earlier, it is a LIFO (Last In First Out) type data structure that can insert and remove data from only one end
This means that the most recently added item to the stack is deleted first.

Maybe you will use Stack for preparing PS (Problem Solving)

Depending on the kind of problem it may be more useful to store data on a stack rather than an array (List)

  • Advantages and disadvantages of stacks
  • There is no need to push the elements sideways one by one like an array.

how to implement?

new Stack

Implemented Stack with Integer Type. very simple

Now let’s see how to use the stack

  • stack.push()
    add value to stack
  • stack.pop()
    Remove top-level(Last entered value) item
  • stack.peek()
    Returns the top-level item But the value is not removed from the stack
  • stack.isEmpty()
    Check if the stack is empty (return : true or false)
  • stack.search()
    Shows index information of the searched value
    If there is no value, -1 is returned.
Stack.java

In what cases should it be used?

  • recursive algorithm
    When a function needs to be called recursively, temporary data is put on the stack
  • visit history
    Because it shows the most recent information first

--

--