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.

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();
    }
}

Stack.java

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() {
        if(list.isEmpty()) {
            return null;
        } else {
            T val = peek();
            list.removeHead();
            return val;
        }
    }
    
    public T push(T val) {
        list.addHead(val);
        return peek();
    }
}