Monday, November 7, 2011

Data Structure - Queue(JAVA) using array


For theoretical reference you check wiki.

http://en.wikipedia.org/wiki/Queue_%28data_structure%29

Java you can refer the code.



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

public class QueueKrk {

 private static final int MAX = 3;
 private static int[] QUEUE = new int[MAX];
 private static int top = -1;
 private static int rear = 0;

 private enum Function {
  PUSH, POP, PRINTALL
 };

 private static void push() {
  if (top < MAX -1) {
   System.out.println("Enter the value to added to the queue");
   int value = readValue();
   QUEUE[++top] = value;
  } else {
   System.out.println("The queue has reached the maximum value");
  }
 }

 private static void peek() {
  if(top >= rear){
   rear++;
  }else{
   System.out.println("Nothing to Peek");
  }

 }

 private static void printAll() {
  if (top >= rear) {
   int i = 0;
   for (i = rear; i <= top; i++) {
    System.out.println(QUEUE[i]);
   }
  } else {
   System.out.println("The queue is empty");
  }
 }

 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;
 }

 public static void main(String[] args) {
  init();
 }

 private static void init() {
  System.out.println("For Push enter 0, Peek 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, Peek , view all respectively");
   init();
  }
  switch (function) {
  case PUSH:
   push();
   init();
   break;
  case POP:
   peek();
   init();
   break;
  case PRINTALL:
   printAll();
   init();
   break;
  default:
   break;
  }
 }

}



No comments:

Post a Comment