Lab Manual
CPCS204
Data Structures 1
Department of Computer Science
1433/1434H
Lab - 6
Learning Procedure
1) Stage J (Journey
inside-out the concept) 2) Stage a
1(apply
the learned)
3) Stage v (verify
the accuracy)
4) Stage a
2(assess
your work)
Laboratory 6:
Statement Purpose:
This lab will give you practical implementation of Queue.
Activity Outcomes:
This lab teaches you the following topics:
Implementation of queue using Array.
Implementation of queue using Linked list concepts.
Instructor Note:
As pre-lab activity, review Ch6, from the book Data Structures with Java by John R. Hubbard and also the relevant instructor’s slides.
Names I.D.
1. .………..………. ………
2. ..……….. ………
3. .………... ………
4. .……….. ..……….
1) Stage J (Journey)
Queue: A queue is different from a stack in that a queue works on a First In First Out (FIFO) basis. In general, items are added to the end of a queue (In the way that we join at the end of a queue for a bus) and items are removed from the front of a queue. (The people at the front of the queue for the bus can get on the bus first.)
The operations that we need to implement a queue are
1. init()//constructor create then initialize queue values and parameters 2. add()
3. remove() 4. isFull() 5. isEmpty()
Queue concept:
Form: http://happy.cs.vt.edu/courses/cs1706/slides/queue.html
A queue is usually depicted horizontally
One end of the queue is the rear (or tail), where elements are added
The other end is the front (or head), from which elements are removed
Unlike a stack, which operates on one end of the collection, a queue operates on both ends
Illustration of the queue concept
A. Implementation of queue using an array representation
i. A queue using an ordinary array
ii. A queue using a circular array
*A simple example to clarify the idea of queue implementation using circular array
B. Implementation of queue using an linked list representation
*In programming of a queue implemented using linked list there exist 3 special cases of are:
A- An empty linkList (Queue) where front = rear = null
B- A linkList (Queue) containing only one item which is the front and also the rear item in the meanwhile
C- In a linkList (Queue) the front and rear node are different two nodes but they are both containing the same item value
2) Stage a
1(apply)
Activity 1:
Apply and test the simple QUEUE implementation using Circular Arrays below:
//A SIMPLE Queue INTERFACE
// Queue.java: is a queue implementation using generic parameterized type E
public interface Queue<E> { public void add(E element);
public E element();
public boolean isEmpty();
public E remove();
public int size();}
// ArrayQueue.java: An ArrayQueue Implementation
public class ArrayQueue<E> implements Queue<E> { private E[] elements;
private int front;
private int back;
private static final int INITIAL_CAPACITY = 4;
public ArrayQueue() {
elements = (E[]) new Object[INITIAL_CAPACITY];
}
public ArrayQueue(int capacity) {
elements = (E[]) new Object[capacity];
}
public void add(E element) {
if (size() == elements.length - 1) { resize();
}
elements[back] = element;
if (back < elements.length - 1) { ++back;
} else {
back = 0; //wrap }
}
public E element() { if (size() == 0) {
throw new java.util.NoSuchElementException();
}
return elements[front];
}
public boolean isEmpty() { return (size() == 0);
}
public E remove() { if (size() == 0) {
throw new java.util.NoSuchElementException();
}
E element = elements[front];
elements[front] = null;
++front;
if (front == back) { // queue is empty front = back = 0;
}
if (front == elements.length) { // wrap front = 0;
}
return element;
}
public int size() {
if (front <= back) { return back - front;
} else {
return back - front + elements.length;
} }
private void resize() { int size = size();
int len = elements.length;
assert size == len;
Object[] a = new Object[2 * len];
System.arraycopy(elements, front, a, 0, len - front);
System.arraycopy(elements, 0, a, len - front, back);
elements = (E[]) a;
front = 0;
back = size;
}
public void printQueue() { System.out.print("[");
String str = "";
if (front <= back) {
for (int i = front; i < back; i++) str += elements[i] + ",";
}
else {
for (int i = front; i < elements.length; i++)
str += elements[i] + ",";
if (back != 0)
for (int i = 0; i < back; i++) str += elements[i] + ",";
}
if (str.length() != 0)
str = str.substring(0, str.length() - 1);
System.out.print(str + "]\n");
} }
// TestStringQueue.java: is a testing a String Queue
public class TestStringQueue {
public static void main(String[] args) {
ArrayQueue<String> queue = new ArrayQueue<String>();
queue.add("GB");
queue.add("DE");
queue.add("FR");
queue.add("ES");
queue.printQueue();
System.out.println("queue.element(): " + queue.element());
System.out.println("queue.remove(): " + queue.remove());
queue.printQueue();
System.out.println("queue.remove(): " + queue.remove());
queue.printQueue();
System.out.println("queue.add(\"IE\"): ");
queue.add("IE");
queue.printQueue();
System.out.println("queue.remove(): " + queue.remove());
queue.printQueue();
} }
The output is:
[GB, DE, FR, ES]
queue.element(): GB queue.remove(): GB [DE, FR, ES]
queue.remove(): DE [FR, ES]
queue.add("IE"):
[FR, ES, IE]
queue.remove(): FR
[ES, IE]
Activity 2:
Apply and test the Queue implementation using LinkedList below which implements the preceding Queue<E> :
// linked List based implementation of the Queue program
public class LinkedQueue<E> implements Queue<E> {
private Node<E> head = new Node<E>(); // dummy node private int size;
public void add(E element) {
head.prev = head.prev.next = new Node<E>(element, head.prev, head);
++size;
}
public E element() { if (size == 0) {
throw new java.util.EmptyStackException();
}
return head.next.element; // front of queue // next
<--> prev }
public boolean isEmpty() { return (size == 0);
}
public E remove() { if (size == 0) {
throw new java.util.EmptyStackException();
}
E element = head.next.element; // next <--> prev head.next = head.next.next; // next <--> prev head.next.prev = head; // next <--> prev
--size;
return element;
}
public int size() { return size;
}
private static class Node<E> { E element;
Node<E> prev;
Node<E> next;
Node() {
this.prev = this.next = this;
}
Node(E element, Node<E> prev, Node<E> next) { this.element = element;
this.prev = prev;
this.next = next;
} } }
Task 1: Consider all given code-blocks above then solve as much as you can of the following problems.
1. Create a new project named QueueTesting and then create the Queue interface and the class (LinkedQueue) written above.
2. Create a main class to test the class LinkedQueue by giving a list of specified values within the main method (see the previous testing file
TestStringQueue
).
3. Add this member method to the ArrayQueue class:
public void reverse()
// reverses the contents of this queue
4. Add this member method to the LinkedQueue class:
public void reverse()
// reverses the contents of this queue
5. Add this member method to the ArrayQueue class:
public E second() {
// returns the second element of this queue
6. Add this member method to the LinkedQueue class shown:
public E second() {
// returns the second element of this queue
7. Add this member method to the ArrayQueue class shown:
public E removeSecond() {
// removes and returns the second element of this queue 8. Add this member method to the LinkedQueue class shown:
public E removeSecond() {
// removes and returns the second element of this queue
3) Stage v (verify)
Programming Exercise
(Optional)Ex-1 (home activity):
Apply and test, and complete required addition subroutine of the Queue implementation using Linked List below:
// linked List based implementation of the Queue program
/***************************************************************
* Compilation: Queue.java * Execution: Queue
* A generic queue, implemented using a linked list. Each queue * element is of type Item.
***************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Queue<Item> implements Iterable<Item> { private int N; // size of the stack private Node first; // beginning of queue private Node last; // end of queue
// helper linked list class
private class Node { private Item item;
private Node next;
}
// create an empty queue
private Node first; // beginning of queue private Node last; // end of queue
//is the queue empty?
public boolean isEmpty() { return first == null; } public int length() { return N; } public int size() { return N; }
// add an item to the queue
public void enqueue(Item item) { Node x = new Node();
x.item = item;
if (isEmpty()) { first = x; last = x; } else { last.next = x; last = x; } N++;
}
// remove and return the least recently added item
public Item dequeue() {
if (isEmpty()) throw new RuntimeException("Queue underflow");
Item item = first.item;
first = first.next;
N--;
return item;
}
// string representation (inefficient because of string concatenation)
public String toString() { String s = "";
for (Node x = first; x != null; x = x.next) s += x.item + " ";
return s;
}
public Iterator<Item> iterator() { return new QueueIterator(); }
// an iterator, doesn't implement remove() since it's optional
private class QueueIterator implements Iterator<Item> { private Node current = first;
public boolean hasNext() { return current != null; } public void remove() { throw new
UnsupportedOperationException(); } public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
} }
// a test client
public static void main(String[] args) {
/***********************************************
* A queue of strings
***********************************************/
Queue<String> q1 = new Queue<String>();
q1.enqueue("Vertigo");
q1.enqueue("Just Lose It");
q1.enqueue("Pieces of Me");
System.out.println(q1.dequeue());
q1.enqueue("Drop It Like It's Hot");
while (!q1.isEmpty())
System.out.println(q1.dequeue());
System.out.println();
/*********************************************************
* A queue of integers. Illustrates autoboxing and * auto-unboxing.
*********************************************************/
Queue<Integer> q2 = new Queue<Integer>();
for (int i = 0; i < 10; i++) q2.enqueue(i);
// test out iterator
for (int i : q2)
StdOut.print(i + " ");
StdOut.println();
// test out dequeue and enqueue
while (q2.size() >= 2) {
int a = q2.dequeue();
int b = q2.dequeue();
int c = a + b;
StdOut.println(c);
q2.enqueue(a + b);
} } }
(Extra) Home Exercise: depending on what you have learned about Queue concepts try to achieve the following.
1. Write a program in Java to implement the concept of queue using an ordinary Array.
2. Your program must implement all the operations of Queue.
4) Stage a
2(assess) Lab Work:
In each laboratory you are assessed on your work within lab session based on your participation, discussions and achievement of lab activities. Thus, each lab has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is used to evaluate your work. This checklist accounts the following criteria:
Following the lab manual step by step
Answering given questions concisely and precisely
Practicing and implementing given examples correctly
Writing code of required programming tasks
Being focused, positive, interactive and serious during lab session
Asking good questions or answering instructor questions if any
Note: performing given home activities or extra programming is highly
recommended to improve your understanding, capability and programming
skills.