01204212/codes/queues and stacks
รุ่นแก้ไขเมื่อ 23:50, 9 กันยายน 2559 โดย Jittat (คุย | มีส่วนร่วม) (หน้าที่ถูกสร้างด้วย ': ''This is part of 01204212'' This part takes linked list class (with iterator) from 01204212/codes/linked_lists to implement...')
- This is part of 01204212
This part takes linked list class (with iterator) from 01204212/codes/linked_lists to implement queues and stacks with the same interface as in the Java Collection.
Queue.java
I also included method printItems which shouldn't be part of the queue class, but it is useful when you debug your code for job queue 2.
import java.util.NoSuchElementException;
public class Queue<T> {
private LinkedList<T> list;
Queue() {
list = new LinkedList<T>();
}
public boolean isEmpty() {
return list.isEmpty();
}
public T peek() {
if(!isEmpty()) {
return list.iterator().getVal();
} else {
return null;
}
}
public T remove() {
T res = poll();
if(res == null) {
throw new NoSuchElementException();
}
return res;
}
public T poll() {
if(! list.iterator().isEnded()) {
T val = peek();
list.removeHead();
return val;
} else {
return null;
}
}
public boolean add(T val) {
list.add(val);
return true;
}
// -------------- additional method for debugging -------
public void printItems() {
LinkedList<T>.Iterator head = list.iterator();
while(head != null) {
System.out.print("" + head.getVal() + " ");
head.next();
}
System.out.println();
}
}