29 Nov 2013

Stack

Problem Statement: 
        Implement Stack

Solution:

Stack supports three main operations:
1. Push:
         Insertion of element
2. Pop:
       Removal of the last element inserted
3. Peek:
 
A stack supports LIFO operations i.e. Last In First Out (LIFO)
These all operations are assisted by the "top" pointer which tracks the top most element element in the stack. 

Fig: Stack of books and Stack of Boxes
-
 /**
 * Stack Implementation
 * @author Prateek Rathore
 *
 */
public class Stack {
 int arr[];
 private static final int DEFAULT_CAPACITY = 10;
 public static int top = -1;
 
 public Stack() {
  arr = new int[DEFAULT_CAPACITY];
 }
 
 public Stack(int size) {
  arr = new int[size];
 }

 public void push(int data) {
  arr[++top] = data;
 }
 public int pop() {
  return arr[top--];
 }

 public int peek() {
           return arr[top];
 }
 
 public boolean isEmpty() {
  if(top==-1)
   return true;
  return false;
 }
}
-

References:
   Refer to one of my friend's post on stacks: LINK
               
Please post your comments and suggestions.

Happy Coding !! :)

No comments:

Post a Comment