Friday, 15 August 2014

Stack and it's important methods



Stack is a collection and it is like a bucket in nature, it works like a bucket to store or retrieve data. Only one end is open to push and pop data elements. Push means putting elements in to stack and pop means retrieve and removing elements from the stack. Stack is a commonly used and efficient data structure with a first in last out capability.




Now some important methods of stack.


public static void main(String[] args) {
           
           //Initializing stack.
        Stack<String> stack=new Stack<String>();
           //pushing elements. 
        stack.push("first");
        stack.push("second");
          printMe(stack);
   
   //Popping objects      
       System.out.println("Popping object : "+stack.pop());
printMe(stack);

  //pushing some more elements.
stack.push("third");
stack.push("fourth");
stack.push("fifth");

   // get first and last elements.

System.out.println("First Element : "+stack.firstElement());
System.out.println("Last Element : "+stack.lastElement());
printMe(stack);

// Insert element on index 1.
System.out.println("Insert element at index 1");
stack.insertElementAt("second",1);
printMe(stack);

//get the top elements.
System.out.println("Peeking object : "+stack.peek());
printMe(stack);

// Remove elements from index 1.
System.out.println("Removing object at index 1 : "+stack.remove(1));
printMe(stack);

//Removing all object from stack.
stack.removeAllElements();
printMe(stack);

}

}


public static void printMe(Stack stack){
if(stack.isEmpty()){
System.out.println("Stack is empty and has nothing to print.");
}else{
   System.out.println("remaining elements : "+stack);

}

}


Output :


No comments:

Post a Comment