Download Queue

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
KING ABDULAZIZ UNIVERSITY
Faculty of Computing & Information Technology
Department of Computer Science
Lab Manual
CPCS204
Data Structures 1
1432/1433H
Lab - 6
Learning Procedure
1)
Stage J (Journey inside-out the concept)
2)
Stage a1 (apply the learned)
3)
Stage v (verify the accuracy)
4)
Stage a2 (assess your work)
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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. .……………………………………………..
..…………………………….
CPCS204 – The Lab Note
Lab-3
1
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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.
2.
3.
4.
5.
init()//constructor create then initialize queue values and parameters
add()
remove()
isFull()
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
CPCS204 – The Lab Note
Lab-3
2
Term I
2011
Lab-6: Queue Using Array and Using Linked List
ii.
A queue using a circular array
*A simple example to clarify the idea of queue implementation using circular array
CPCS204 – The Lab Note
Lab-3
3
Term I
2011
Lab-6: Queue Using Array and Using Linked List
CPCS204 – The Lab Note
Lab-3
4
Term I
2011
Lab-6: Queue Using Array and Using Linked List
B. Implementation of queue using an array 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
CPCS204 – The Lab Note
B- A linkList (Queue) containing
only one item which is the
front and also the rear item
in the meanwhile
Lab-3
C- In a linkList (Queue) the front and
rear node are different two nodes
but they are both containing the
same item value
5
Term I
2011
Lab-6: Queue Using Array and Using Linked List
2) Stage a1 (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
private
private
private
E[] elements;
int front;
int back;
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();
}
CPCS204 – The Lab Note
Lab-3
6
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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++)
CPCS204 – The Lab Note
Lab-3
7
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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) {
Queue<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]
CPCS204 – The Lab Note
Lab-3
8
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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() {
CPCS204 – The Lab Note
Lab-3
9
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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
TestStringStack).
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
CPCS204 – The Lab Note
Lab-3
10
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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;
private Node last;
// beginning of queue
// 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++;
CPCS204 – The Lab Note
Lab-3
11
Term I
2011
Lab-6: Queue Using Array and Using Linked List
}
// 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()
QueueIterator(); }
{ return new
// 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");
CPCS204 – The Lab Note
Lab-3
12
Term I
2011
Lab-6: Queue Using Array and Using Linked List
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.
CPCS204 – The Lab Note
Lab-3
13
Term I
2011
Lab-6: Queue Using Array and Using Linked List
4) Stage a2 (assess)
Lab Report:
The laboratory report of this lab (and also all the following labs in this manual)
should include the following items/sections:
 A cover page with your name, course information, lab number and title,
and date of submission.
 A summary of the addressed topic and objectives of the lab.
 Implementation: a brief description of the process you followed in
conducting the implementation of the lab scenarios.
 Results obtained throughout the lab implementation, the analysis of these
results, and a comparison of these results with your expectations.
 Answers to the given exercises at the end of the lab. If an answer
incorporates new graphs, analysis of these graphs should be included here.
 A conclusion that includes what you learned, difficulties you faced, and any
suggested extensions/improvements to the lab.
Note: only a softcopy is required, please do not print or submit a hard copy.
CPCS204 – The Lab Note
Lab-3
14