01: package jsint;
02:
03: /** A queue, q, is a Pair (cons ,last ,content), see Peter's, PAIP book.
04:
05: <p> This lets .add() be written without a null comparison, but
06: uses an extra Pair.
07:
08: <p>Used by InputPort.readTail and U.append.
09: **/
10: public class Queue {
11: private Pair q;
12:
13: /** Create an empty Queue. **/
14: public Queue() {
15: q = new Pair(null, Pair.EMPTY);
16: q.first = q;
17: }
18:
19: /** Create a Queue containing the single element, item. **/
20: public Queue(Object item) {
21: this ();
22: this .add(item);
23: }
24:
25: /** Get the last Pair of the Queue's content. **/
26: public Pair getLast() {
27: return ((Pair) q.first);
28: }
29:
30: /** Get the Queue's content as a Pair list. **/
31: public Object getContent() {
32: return q.rest;
33: }
34:
35: /** Add an item to the end of the Queue. **/
36: public Queue add(Object item) {
37: Pair last = new Pair(item, Pair.EMPTY);
38: this .getLast().rest = last;
39: q.first = last;
40: return this ;
41: }
42:
43: /** Remove an item from the front of the Queue. **/
44: public Queue remove() {
45: if (U.isPair(q.rest))
46: q.rest = U.rest(q.rest);
47: if (!U.isPair(q.rest))
48: q.first = q;
49: return this ;
50: }
51:
52: /** Return the first item in the Queue, or null if the Queue is empty. **/
53: public Object front() {
54: Object c = this .getContent();
55: if (U.isPair(c))
56: return U.first(c);
57: else
58: return null;
59: }
60:
61: public Object pop() {
62: Object result = this.front();
63: this.remove();
64: return result;
65: }
66: }
|