In this section, you will learn how to implement a stack in Java.
Implementing a Stack in Java
In this section, you will learn how to implement a stack in Java. A Stack is like a bucket in which you can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method.
This program implements a stack and follows the LIFO rule. It asks you for the number of elements which have to be entered in the stack and then it takes elements for insertion in the stack. All the elements present in the stack are shown from the last inserted element to the first inserted element.
Stack<Integer>():
Above constructor of the Stack class creates a empty stack which holds
the integer type value which is mention with the creation of stack. The Stack
class extends the Vector class and both classes are implemented from the java.util.*;
package.
Stack.push(Object obj):
Above method is used to insert or push the data or
element in the stack. It takes an object like: data or elements and push its
onto the top of the stack.
Stack.pop():
This is the method to removes the objects like:
data or elements at the top positions of stack.
Here is the code of program:
import java.io.*;
|