设计模式之不变设计模式(四)
* @param e
* @return
* @throws IllegalArgumentException
*/
public PersistentQueue enqueue(E e) {
return new PersistentQueue<>(outgoing, incoming.push(e));
}
/**
* Returns the queue that removes the object at the head of this queue
* without modifying this queue.
*
*
* e.g.
* When this queue represents the queue (7, 1, 3, 3, 5, 1) ,
* this method returns a new queue (1, 3, 3, 5, 1)
* and this object still represents the queue (7, 1, 3, 3, 5, 1) .
*
*
* If this queue is empty, throws java.util.NoSuchElementException.
*
*
* How to dequeue works:
* 1) if both incoming stack and outgoing stack are empty, just throws java.util.NoSuchElementException.
* 2) if only the outgoing stack is empty, we first reverse the incoming stack as outgoing stack @see PersistentStack#reverse(), then pop from outgoing stack.
* 3) if outgoing stack is not empty, just pop from outgoing stack.
*
*
* @return
* @throws java.util.NoSuchElementException
*/
public PersistentQueue dequeue() {
if (isEmpty()) // both empty
throw new NoSuchElementException();
else if (outgoing.isEmpty()) { // only the outgoing stack is empty
PersistentStack stack = incoming.reverse().pop();
return new PersistentQueue(stack, new PersistentStack());
}// end if
else
// both are not empty
return new PersistentQueue<>(outgoing.pop(), incoming);
} // end dequeue()
/**
* Looks at the object which is the head of this queue without removing it
* from the queue.
*
*
* e.g.
* When this queue represents the queue (7, 1, 3, 3, 5, 1),
* this method returns 7 and this object still represents the queue (7, 1, 3, 3, 5, 1)
*
*
* If the queue is empty, throws java.util.NoSuchElementException.
*
* @return
* @throws java.util.NoSuchElementException
*/
public E peek() {
if (isEmpty()) // both empty
throw new NoSuchElementException();
else if (outgoing.isEmpty()) { // outgoing is empty, but incoming not
// empty
return incoming.reverse().peek();
}// end if
else
return outgoing.peek();
}// end peek()
/**
* Returns the number of objects in this queue.
*
* @return
*/
public int size() {
return (outgoing.size() + incoming.size());
} // end size()
/**
* Returns true if this persistent stack contains no elements.
*
* @return
*/
public boolean isEmpty() {
return (size() == 0);
}// end isEmpty()
}// end class
在前面写的基础上实现添加一个队列的函数
[java
public ExamImmutableQueue append(ExamImmutableQueue queue){
ExamImmutableQueue temp=queue;
ExamImmutableQueue result=this;
if(!queue.isEmpty()){
for(int i=0;i
q.add(temp.peek());
temp=temp.dequeue();
}//end for
}//end if
return result;
} //end append()