queandstacks
QuesandStack/quehomework.docx
import java.util.*;
import static java.lang.System.out;
public class QueueTest1
{
public static void main(String[] args)
{
Queue<String> stringQueue = new QueueImpl<String>();
// Prints null Fred Fred Suzy Barney Wilma
out.println(stringQueue.peek());
stringQueue.add("Fred");
stringQueue.add("Suzy");
stringQueue.add("Barney");
stringQueue.add("Wilma");
out.println(stringQueue.peek());
String s = stringQueue.remove();
while(s != null)
{
out.println(s);
s = stringQueue.remove();
}
Queue<Double> queue = new QueueImpl<Double>();
// Prints null 3.14 3.14 1.77 4.68 9.99
out.println(queue.peek());
queue.add(3.14);
queue.add(1.77);
queue.add(4.68);
queue.add(9.99);
out.println(queue.peek());
Double d = queue.remove();
while(d != null)
{
out.println(d);
d = queue.remove();
}
}
}
interface Queue<E>
{
// Add places an element at the tail
// of the queue.
void add(E e);
// Takes the element at the head out
// of the queue and returns it. Returns
// null if queue is empty.
E remove();
// Same as remove, except leaves
// the element in the queue
E peek();
}
class QueueImpl<E> implements Queue<E>
{
// Create an instance of a LinkdedList below,
// which you will use for storage and retrieval
// in creating your Queue implementation. Then
// code the three methods required by the Queue
// interface above.
}
QuesandStack/stackhomework.docx
import java.util.*;
import static java.lang.System.*;
public class StackTest
{
public static void main(String[] args)
{
Stack<Integer> integerStack = new StackImpl<Integer>();
// Should print 15 7 4 9
integerStack.push(9);
integerStack.push(4);
integerStack.push(15);
out.println(integerStack.pop());
integerStack.push(7);
while(!integerStack.empty())
{
out.println(integerStack.pop());
}
Stack<String> stringStack = new StackImpl<String>();
// Should print null null Maria Maria Tom Suzy Fred
out.println(stringStack.peek());
out.println(stringStack.pop());
stringStack.push("Fred");
stringStack.push("Suzy");
stringStack.push("Tom");
stringStack.push("Maria");
out.println(stringStack.peek());
while(!stringStack.empty())
{
out.println(stringStack.pop());
}
}
}
interface Stack<E>
{
// Places element e at the top of the stack
void push(E e);
// Removes the element at the top of the stack and returns it.
// Returns null if the stack is empty.
E pop();
// Returns the element at the top of the stack, without removing it.
// Returns null if the stack is empty.
E peek();
// Returns true if the stack is empty, otherwise false.
boolean empty();
}
class StackImpl<E> implements Stack<E>
{
private ArrayList<E> list = new ArrayList<E>();
// Using the above ArrayList as your storage,
// implement all 4 necessary methods of your
// generic stack data structure.
}