/* Modularly optimizing a basic Queue (of strings) implementation */ class node // basic linked list class { private String item; node next; // public within package/compilation unit ("internal" in C#) public node(String i, node n) { item=i; next=n; } // constructor public String item() { return item; } // accessor method for item }// basic linked list class // wrapper class for queue (first in last out) class queue { private node first; // pointer to first node public queue() { first=null; } // start with empty queue // insert x into queue from the back public void enqueue(String x) { node nx = new node(x,null); // new node to be inserted if (first==null) { first = nx; return; } node i = first; while (i.next!=null) i=i.next; i.next = nx; }// enqueue public String dequeue() // delete from front { if (first==null) throw new Error("empty queue"); String ax = first.item(); first = first.next; return ax; } // compute size of queue public int size() { int cx = 0; for(node i=first; i!=null; i=i.next) cx++; return cx; } public void printqueue() { for(node i=first;i!=null;i=i.next) System.out.print(i.item()+" "); System.out.println(); } }//queue public class aoplists { public static void main(String[] av) { queue Q = new queue(); Q.enqueue("Sakib"); Q.enqueue("Tailor"); Q.enqueue("Denson"); Q.enqueue("J"); Q.enqueue("Noel"); Q.printqueue(); System.out.println(Q.dequeue()); System.out.println(Q.size()); }//main } //////////////////// aspect to optimize Queue implementation privileged aspect optimizequeue { node queue.last; // add last pointer to queue class int queue.size; // add size constant for easy size lookup after(queue q) : execution(node.new()) && target(q) { q.last = null; q.size = 0; } int around(queue q) : call(public int queue.size()) && target(q) { return q.size; } after(queue q) : call(public String queue.dequeue()) && target(q) { if (q.first==null) q.last = null; q.size--; } void around(queue q, String x) : call(public void queue.enqueue(String)) && target(q) && args(x) { node nx = new node(x,null); if (q.last==null) { q.first=q.last = nx; q.size=1; return; } q.last.next = nx; q.last = nx; q.size++; System.out.println("new enqueue executed"); // trace } // illustrating withincode predicate private node newnode = null; // private within aspect after(node n) : execution(node.new(..)) && withincode(public void queue.enqueue(..)) && target(n) { newnode = n; // capture new node so it can be used for next advice... } }//privileged aspect optimize queue /* Challenge: change list to doubly linked list, then implement a method "pop" that deletes from the back of the queue (change last pointer.) This operation must run in O(1) time. */