雖然原本的Java就有這個東西了,但是還是實作一下。
class JElemrnt{ public JElemrnt prev; public T value; public JElemrnt next; public JElemrnt(T t) { prev = null; next = null; value = t; } } public class JQueue { JElemrnt head; JElemrnt tail; int queueSize; public JQueue() { queueSize = 0; head = null; tail = null; } public void enqueue(T t) { JElemrnt tmp = new JElemrnt (t); if(queueSize == 0) { head = tmp; tail = tmp; } else { tmp.prev = tail; tail.next = tmp; tail = tmp; } ++queueSize; System.out.println("Enqueue Element: " + t.toString()); System.out.println("Now queue size is: " + queueSize); } public T dequeue() { if(head == null || tail == null) { return null; } T retVal = tail.value; tail = tail.prev; //tail.next = null; --queueSize; System.out.println("Dequeue Element: " + retVal.toString()); System.out.println("Now queue size is: " + queueSize); if(queueSize == 0) { head = null; tail = null; } return retVal; } public T query(int n) { if(n > queueSize) return null; return null; } public static void main(String[] argv) { System.out.println("Starting queue demo..."); JQueue q = new JQueue (); Integer i1 = new Integer(1); Integer i2 = new Integer(2); Integer i3 = new Integer(3); q.enqueue(i1); q.enqueue(i2); Integer de = q.dequeue(); q.enqueue(i3); de = q.dequeue(); de = q.dequeue(); System.out.println("Ending queue demo..."); } }
沒有留言:
張貼留言