package edu.columbia.cs.cs1007.datastructures;
import java.util.Queue;
import java.util.Stack;
import java.util.LinkedList;
/**
* Demonstrate the features of the Java implementation of
* LinkedList, Stack and Queue
* @author Julia Stoyanovich, jds2109@columbia.edu
* COMS 1007, Summer 2009
*
*/
public class StackAndQueueDemo {
/**
* This method uses Java's built-in Stack to
* reverse elements in an array
* @param inArr
* @return array in reverse order
*/
public static int[] reverseArray(int[] inArr) {
Stack<Integer> stack = new Stack<Integer>();
int[] outArr = new int[inArr.length];
for (int num : inArr) {
stack.push(new Integer(num));
}
int i=0;
while (!stack.isEmpty()) {
outArr[i++] = stack.pop();
}
return outArr;
}
/**
* This method uses the stack that we implemented
* to reverse elements in an array.
* @param inArr
* @return array in reverse order
*/
public static int[] myReverseArray(int[] inArr) {
MyStack stack = new MyStack();
int[] outArr = new int[inArr.length];
for (int num : inArr) {
stack.push(new Integer(num));
}
int i=0;
while (!stack.isEmpty()) {
outArr[i++] = stack.pop();
}
return outArr;
}
public static void queueDemo(int[] inArr) {
Queue<Integer> queue = new LinkedList<Integer>();
for (int i=0; i<inArr.length; i++) {
queue.offer(inArr[i]);
if ((i%2 == 0) && (queue.peek() > 2)) {
queue.offer(inArr[i]);
}
if (queue.peek() > 3) {
queue.poll();
}
}
}
public static String arrayToString(int[] inArr) {
StringBuffer res = new StringBuffer();
for (int i=0; i<inArr.length; i++) {
res.append(inArr[i] + " ");
}
return res.toString();
}
public static void main(String [] args) {
int[] inArr = {1, 2, 3, 4, 5};
System.out.println(arrayToString(inArr));
int[] outArr = reverseArray(inArr);
System.out.println(arrayToString(outArr));
outArr = myReverseArray(inArr);
System.out.println(arrayToString(outArr));
}
}
|