Java链接列表优先级队列

时间:2013-11-08 02:12:31

标签: java

有序链表实现

这是我编写的代码由于某种原因它不会编译并要求主函数。我使用了一个main函数来测试它,但是我需要这个程序。

package data_structures;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ListPriorityQueue<E> implements PriorityQueue<E> {

private Node head;
private int size;

private class Node {
    private E value;
    private Node next;
    public Node(E value, Node next) {
        this.value = value;
        this.next = next;
        }
    }

private class NodeIter implements Iterator<E> {
    private E[] arr;
    private int n;

    public NodeIter() {
        n = size;
        arr = (E[]) new Object[n];
        Node p = head;
        for (int i = 0; i < n; ++i) {
            arr[i] = p.value;
            p = p.next;
            }
        }
    public boolean hasNext() { 
        return n > 0; 
        }
    public E next() {
        if (n == 0) 
            throw new NoSuchElementException();
        return arr[--n];
        }
    public void remove() { 
        throw new UnsupportedOperationException(); 
        }
    }

public ListPriorityQueue() {
    this.head = null;
    this.size = 0;
    }

public boolean insert(E object) {
    if (isFull()) 
        return false;
    if (head == null) {
        head = new Node(object, null);
        } 
    else if (((Comparable<E>)object).compareTo(head.value) < 0) {
        head = new Node(object, head);
        } 
    else {
        Node p = head;
        while (p.next != null && ((Comparable<E>)object).compareTo(p.next.value) >= 0) {
            p = p.next; //or equal to preserve FIFO on equal items
            }
        p.next = new Node(object, p.next);
        }
    ++size;
    return true;
    }

public E remove() {
    if (isEmpty()) 
        return null;
    E value = head.value;
    head = head.next;
    --size;
    return value;
    }

public E peek() {
    if (isEmpty()) 
        return null;
    return head.value;
    }

public int size() {
    return size;
    }

public boolean contains(E object) {
    Node p = head;
    while (p != null) {
        if (((Comparable<E>)object).compareTo(p.value) == 0)
            return true;
        p = p.next;
        }
    return false;
    }

public Iterator<E> iterator() {
    if (isEmpty()) 
        return null;
    return new NodeIter();
    }

public void clear() {
    head = null;
    size = 0;
    }

public boolean isEmpty() {
    return size == 0;
    }

public boolean isFull() {
    return size == DEFAULT_MAX_CAPACITY;
    }
}

1 个答案:

答案 0 :(得分:0)

使用javac很好地编译。我假设您无法将其作为控制台应用程序运行。这是不可能的,因为Java控制台应用程序需要方法 public static void main(String[] args) 哦,有一些关于未经检查的类型转换的警告