2016-05-12 3 views
0

私はリンクリストを使用して汎用キューを実装しています。私は以下のメソッドを持っています:enqueue、dequeueそしてpeek。私は、キュー内の最小値を見つけて、キューが空であれば例外をスローするメソッドを書くのに助けが必要です。汎用キュー、最小値を見つける方法

私がこれまで持っているコードは次のとおりです。

class Queue <T> 
{ 
    private Node front, rear; //begin and end nodes 
    private int size; // number of items 

    //nested class to define node 
    private class Node 
    { 
    T item; 
    Node next; 
    } 

    //Zero argument constructor 
    public Queue() 
    { 
    front = null; 
    rear = null; 
    size = 0; 
    } 

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

    //peek method 
    public T peek(){ 


     T item = front.item; 
     return item; 
    } 

    //Remove item from the beginning of the list. 
    public T dequeue() 
    { 
    T item = front.item; 
    front = front.next; 
    if (isEmpty()) 
    { 
     rear = null; 
    } 
    size--; 
    return item; 
    } 

    //Add T to the end of the list. 
    public void enqueue(T item) 
    { 
    Node oldRear = rear; 
    rear = new Node(); 
    rear.item = item; 
    rear.next = null; 
    if (isEmpty()) 
    { 
     front = rear; 
    } 
    else 
    { 
     oldRear.next = rear; 
    } 
    size++; 
    } 

    public int size() 
    { 
    return size; 
    } 
//finds the maximum and minimum in the list 
//assumes that head pointer is defined elsewhere 

    public static void main (String a[]) 
    { 
    Queue <Integer> q = new Queue<Integer>(); 
    q.enqueue(20); 
    q.enqueue(30); 
    q.enqueue(40); 
    q.enqueue(50); 
    q.enqueue(60); 
    q.enqueue(70); 


    System.out.println("Delete an item from queue: " + q.dequeue());  
    System.out.println("Size of the queue: " + q.size()); 
    System.out.println("Size of the queue: " + q.peek()); 

    } 

} 
+0

追加を投げています最小値と例外を見つける必要がありますstacktraceとスローされた行をマーク – Jens

+1

あなたの質問は何ですか? _私はhelp_が必要ではありません。 [どうすれば良い質問をしますか?](http://stackoverflow.com/help/how-to-ask)をお読みください。 –

答えて

0

以下のメソッドは、キューが 空である場合、私は、カスタム「QueueEmptyException」

public Integer findMin(Queue q){ 
    if (q.size == 0) 
     throw new QueueEmptyException(); 

Integer min = q.front.item; 
While (q.front.next != null) { 
    if (min > q.front.next.item) { 
     min = q.front.next.item 
     q.front = q.front.next; 
    } 
return min; 
関連する問題