VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-implement-stack-api/

⇱ Java Program to Implement Stack API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Implement Stack API

Last Updated : 27 Jul, 2022

A stack is a linear data structure that follows a particular order in which insertion/deletion operations are performed. The order is either LIFO(Last In First Out) or FILO(First In Last Out). Stack uses the push() function in order to insert new elements into the Stack and pop() function in order to remove an element from the stack. Insertion and removal in the stack are allowed at only one end called Top. Overflow state in the stack occurs when it is completely full and Underflow state in the stack occurs when it is completely empty.

Example:

Input:

 stack.push(1)
 stack.push(2)
 stack.pop()
 stack.peek()

Output:
2
2

Syntax:

public class Stack<E> extends Vector<E>

Stack API implements

Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess.

Methods in Stack:

  1. empty() - Tests if this stack is empty.
  2. peek() - Looks at the object at the top of this stack without removing it from the stack.
  3. pop() - Removes the object at the top of this stack and returns that object as the value of this function.
  4. push(E item) - Pushes an item onto the top of this stack.
  5. int search(Object o) - Returns the 1-based position where an object is on this stack.

Below is the implementation of the problem statement:

 
 


Output
element pushed : one
element pushed : two
element pushed : three
element pushed : four
element pushed : five
element popped : five
element popped : four
Element peek : three
position of element three - 1
element popped : three
element popped : two
element popped : one


 

Comment