Advertisement
| Stack<Type> st = new Stack<Type> | 
|---|
| This constructor creates an empty Stack of a certain Type, where Type could be any class. For example - | 
Stack <Integer> s = new Stack <Integer>();| Methods | Description | 
|---|---|
| int size() | Returns the total number of elements in Stack. | 
| boolean empty() | Returns true if Stack is empty, else false. | 
| E push(E element) | Pushes the element on the top of Stack. | 
| E pop() | Returns and removes the element from the top of Stack | 
| E peek() | Returns but doesn't remove element from the top of Stack. | 
| int search(Object element) | Returns the index of an element(if found), else -1 is returned. | 
Advertisement
//Java - Example of Stack 
import java.util.*;
class Stack1
{
public static void main(String... ar)
{
	//Calling the constructor of Stack 
	Stack<Integer> st= new Stack<Integer>();
	
	//Calling the push() method to push new objects in Stack
	st.push(10);
	st.push(23);
	st.push(16);
	st.push(5);
	st.push(29);
	//Printing the elements of the Stack 
	System.out.println("Contents of Stack = "+ st);
	//Calling the pop() method to pop the current top element of the Stack
	System.out.println("Popping out the top element = "+ st.pop());
	System.out.println("Popping out the next top element = "+ st.pop());
	//Priting the updated elements of the Stack
	System.out.println("Updated contents of Stack = "+ st);
	//Calling the peek() method of the Stack to print the top element of the Stack without removing it.
	System.out.println("Peeking at the top element = "+ st.peek());
	//Calling the search() method to search an element within the Stack.
	System.out.println("Index of element 5 from the top = "+st.search(5));
}
}
Contents of Stack = [10, 23, 16, 5, 29]
Popping out the top element = 29
Popping out the next top element = 5
Updated contents of Stack = [10, 23, 16]
Peeking at the top element = 16
Index of element 5 from the top = 3
 
  
Advertisement 
Advertisement
Please check our latest addition
 
 
  C#, PYTHON and DJANGO 
Advertisement