JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Stack implementation in java data structure and algorithm

Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using Array.
Although java provides implementation for all abstract data types such as Stack,Queue and LinkedList but it is always good idea to understand basic data structures and implement them yourself.


Java Program to implement Stack using Array:

package org.arpit.java2blog;

/**
 * @author java Gian
 */
public class StackCustom {
int size;
int arr[];
int top;

StackCustom(int size) {
this.size = size;
this.arr = new int[size];
this.top = -1;
}

public void push(int pushedElement) {
if (!isFull()) {
top++;
arr[top] = pushedElement;
System.out.println("Pushed element:" + pushedElement);
} else {
System.out.println("Stack is full !");
}
}

public int pop() {
if (!isEmpty()) {
int returnedTop = top;
top--;
System.out.println("Popped element :" + arr[returnedTop]);
return arr[returnedTop];

} else {
System.out.println("Stack is empty !");
return -1;
}
}

public int peek() {
if(!this.isEmpty())
                        return arr[top];
                else
                {
                        System.out.println("Stack is Empty");
                        return -1;
                }
}

public boolean isEmpty() {
return (top == -1);
}

public boolean isFull() {
return (size - 1 == top);
}

public static void main(String[] args) {
StackCustom StackCustom = new StackCustom(10);
StackCustom.pop();
System.out.println("=================");
StackCustom.push(10);
StackCustom.push(30);
StackCustom.push(50);
StackCustom.push(40);
System.out.println("=================");
StackCustom.pop();
StackCustom.pop();
StackCustom.pop();
System.out.println("=================");
}
}

When you run above program, you will get below output:



Stack is empty !
=================
Pushed element:10
Pushed element:30
Pushed element:50
Pushed element:40
=================
Popped element :40
Popped element :50
Popped element :30
=================

.