|
|
Structs
/csbook/solutions/03/A11.cs
using System;
class OverflowException: Exception {}
class UnderflowException: Exception {}
// generic queue
struct Queue {
object[] values;
int size, head, tail;
public Queue(int size) {
this.size = size;
values = new object[size];
head = tail = 0;
}
public void Enqueue(object x) {
int tail1 = (tail + 1) % size;
if (tail1 == head) throw new OverflowException();
values[tail] = x;
tail = tail1;
}
public object Dequeue() {
if (head == tail) throw new UnderflowException();
object x = values[head];
head = (head + 1) % size;
return x;
}
public int Length() {
return (tail + 10 - head) % size;
}
}
// program that uses a queue to store integers and strings
class Test {
public static void Main() {
Queue q = new Queue(10);
q.Enqueue(1); q.Enqueue(2); q.Enqueue(3);
while (q.Length() > 0) {
Console.Write((int)q.Dequeue() + " ");
}
Console.WriteLine();
q.Enqueue("Alice"); q.Enqueue("Bob"); q.Enqueue("Charly");
while (q.Length() > 0) {
Console.Write((string)q.Dequeue() + " ");
}
Console.WriteLine();
}
}
|
|