© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu
Quick Links
Easy Studies

Stack Implementation Using Java

Description:

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 take 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. The Stack class extends the Vector class and both classes are implemented from the java.util package.

Stack This constructor creates an empty stack which holds the integer type value which is mention with the creation of stack. Stack. Push (Object obj) method is used to insert or push the data or element in the stack. It takes an object like data or elements and pushes it onto the top of the stack. Stack. pop () method removes the objects like data or elements at the top positions of stack.

Stack Implementation Using Java:

import java.io.*; import java.util.*; public class StackImplement{ Stack stack; String str; int num, n; public static void main(String[] args){ StackImplement q = new StackImplement(); } public StackImplement(){ try{ stack = new Stack(); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.print("Enter number of elements : "); str = bf.readLine(); num = Integer.parseInt(str); for(int i = 1; i <= num; i++){ System.out.print("Enter elements : "); str = bf.readLine(); n = Integer.parseInt(str); stack.push(n); } } catch(IOException e){} System.out.print("Retrieved elements from the stack : "); while (!stack.empty()){ System.out.print(stack.pop() + " "); } } }

Sample ScreenShot:

 
SLogix Student Projects

⇓Student Projects⇓
⇑Student Projects⇑
bottom