Stack methods

  • Eclipse: Oxygen
  • Java: 1.8

The useful stack methods that are a push, pop and search along with empty () are shown here. These methods are used to perform basic operations. In this tutorial, users will learn how to define a stack along with the use of all the above-stated methods.

The following program will demonstrate stack methods:

A stack of Integer type is created, the push method is used to push element in the stack. A foreach loop is used to iterate through all the elements of the stack.

Output

0

1

2

3

4

5

pop() method is always performed on the top of stack element. If we perform pop() operation, it will remove the top element of the stack.

Output

0

1

2

3

4

Peek() method is used to check the last element of the stack.

We can also check if empty or not by using the empty() method.

Output

Stack is not empty

We can also perform a search operation on stack. Search() method returnsĀ  1 if it finds the searched element and it returns -1 if it does not find the searched element.

Output

Stack is not empty

-1

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu