Wednesday, May 6, 2009

Stack Using Array, Java Implementation of Langsam & Tanenbaum's Data Structure

I read my senior's post whom a lecturer in surabaya about stack using array, he is using C. I remember that problem arise in Data Structure when I was in bachelor, taken from Yedidyah Langsam and Andrew S. Tanenbaum's book. So I rewrite his code in java version. Feels great that you try to remembering what you learn for past years, and in fact at that time I donot understand at all about the subject.

package stack.queue;

import java.io.IOException;
import java.util.Scanner;

public class StackFromArray {
final static int MAX = 5;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);

int stack[] = new int[MAX];
int top = -1;
int choice = 0;
do {
System.out.println("\n*******************************");
System.out.println("Menu:");
System.out.println("1. PUSH\t2. POP\t3. VIEW\t4. EXIT");
System.out.println("*******************************");
System.out.print("Please Choose Menu : ");
choice = scanner.nextInt();
switch (choice) {
case 1: //push
if (top >= MAX - 1)
System.err.println("Stack is full");
else {
System.out.print("Data You want to push : ");
int data = scanner.nextInt();
System.out.println("You pushed " + data);
stack[top + 1] = data;
top++;
}
break;
case 2: //pop
if (top < 0)
System.out.println("Stack is empty");
else {
System.out.print("Data out = " + stack[top]);
top--;
}
break;
case 3: //view
for (int i = 0; i < stack.length; i++)
System.out.print(stack[i] + " ");
System.out.println("\n");
break;
case 4: //view
System.out.println("Exit...\n");
break;
default:
break;
}
} while (choice != 4);
System.err.println("Program terminated");
}
}

No comments: