http://en.wikipedia.org/wiki/Stack_%28data_structure%29
Java Stack using array .
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StackKrk {
private static final int MAX = 3;// constant for the size of the stack.
private static final int[] STACK = new int[MAX];
private static int TOP = 0; // Flag for the stack position.
private enum Function{PUSH, POP, PRINTALL};
public static void main(String[] args) {
init();
}
private static void init(){
System.out.println("For Push enter 0, Pop enter 1 and 2 to print all. For exit enter non number");
int selection = readValue();
optionSelection(selection);
}
private static void optionSelection(int selection){
Function function = null;
try{
function = Function.values()[selection];
}catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Enter either '0' or '1' or '2' for push, pop , view all respectively");
init();
}
switch (function) {
case PUSH:
push();
init();
break;
case POP:
pop();
init();
break;
case PRINTALL:
printAll();
init();
break;
default:
break;
}
}
private static int readValue() {
int input = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = Integer.parseInt(br.readLine());
} catch (NumberFormatException nfe) {
System.err.println("Invalid Format!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
return input;
}
private static void push() {
if (TOP == MAX) {
System.out.println("Reached the maximum stack value");
} else {
System.out.println("Enter the value to be pushed ::>");
int value = readValue();
STACK[TOP++] = value;
}
}
private static void pop() {
if (TOP == 0) {
System.out.println("The stack is empty");
} else {
System.out.println("The poped element of the stack ::>" + STACK[--TOP]);
STACK[TOP] = 0;
}
}
private static void printAll(){
for(int i=0; i<=TOP-1; i++){
System.out.println("Value in the stack position["+i+"] "+STACK[i]);
}
}
}
No comments:
Post a Comment