Friday, December 29, 2017

Stack in java


Its a child class of Vector. it is designed the class for LIFO last in first out order.

Constructors :
  1. Stack s=new Stack();

                                                     
 
offset Stack index
1 D 3
2 C 2
3 B 1
4 A 0

methods:

 1. object push(object o)
      to insert an object into the stack.
 2. object pop()
     to remove an object and returns top of the stack object.
3.  object peek()
    to return top of the stack without removal.
4. Boolean empty()
   return true if the stack is empty.
5. int search(object o)
   returns offset if the element is available otherwise -1.

note : stack is extends vector so all methods of vector class are available for the stack too.


example :


package indrajeet.list.exp;

import java.util.Stack;

public class StackExp {

public static void main(String[] args) {

Stack s=new Stack<>();
s.push(3);
s.push("indajeet");
s.add(3);

System.out.println(s);
System.out.println(s.peek());// return top of the element without removal
System.out.println(s);
System.out.println(s.pop());//return top of the element with removal
System.out.println(s);
System.out.println(s.search(2));// returns offset if element is available otherwise -1


}

}

output :

[3, indajeet, 3]
3
[3, indajeet, 3]
3
[3, indajeet]
-1


No comments: