Thursday, April 26, 2012

Stack Implementation in Java without use of collection.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class stack3 {

/**
 * @param args
 * @return
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
System.out.println("Enter Your Choice - \n1.Push \n2.Pop \n3.Display \n4.Exit");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int choice = 0;
do {
System.out.println("Select Your Choice : ");
choice = Integer.parseInt(br.readLine());
System.out.println("Choice - " + choice);
switch (choice) {
case 1:
System.out.println("\tElement to be Pushed : ");
int val = Integer.parseInt(br.readLine());
System.out.println("Value - " + val);
push(val);
break;
case 2:
val = pop();
if (val != -1)
System.out.println("\tPopped Element: " + val);
break;
case 3:
display();
break;
case 4:
System.out.println("Exiting program");
break;
default:
System.out.println("\tWrong Choice");
break;
}
} while (choice != 4);
return;
}

static int maxsize = 100;

static int stack[] = new int[maxsize];
static int stacktop = 0;

static void push(int val) {
System.out.println("Push Value - " + val);
if (stacktop < maxsize)
stack[stacktop++] = val;
else
System.out.println("Stack Overflow");
}

static int pop() {
int a;
if (stacktop > 0) {
stacktop--;
a = stack[stacktop];
return a;
} else {
System.out.println("Stack is Empty");
return -1;
}
}

static void display() {
int displayStack = stacktop;
if (displayStack > 0) {
System.out.println("Elements in the stack are :");
while (displayStack>0) {
System.out.println("Element [" +displayStack + "]:" + stack[--displayStack]);
}
} else
System.out.println("Stack is Empty\n");
}

}