01204212/codes/queues and stacks

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
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. Some method is intentionally left out as an exercise.

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. Method poll has been left out as an exercise. Note that method poll removes the head of the queue and returns it, but if the queue is empty it returns null.

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() {
         // put your code here
    }
    
    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();
    }
}

Stack.java

Method pop that returns and removes the top of the stack has been left out as an exercise.

public class Stack<T> {

    private LinkedList<T> list;
    
    Stack() {
        list = new LinkedList<T>();
    }
    
    public boolean empty() {
        return list.isEmpty();
    }
    
    public T peek() {
        if(list.isEmpty()) {
            return null;
        } else {
            return list.iterator().getVal();
        }
    }
    
    public T pop() {
        // ... put your code here ...
    }
    
    public T push(T val) {
        list.addHead(val);
        return peek();
    }
}