开发者

How to start a output restricted double ended queue in Java?

开发者 https://www.devze.com 2023-02-08 10:17 出处:网络
I was trying to figure out how to start writing a double ended queue with restricted output usin开发者_Python百科g Java, so I can input elements from both ends but remove them from just one.

I was trying to figure out how to start writing a double ended queue with restricted output usin开发者_Python百科g Java, so I can input elements from both ends but remove them from just one. I have done single queues, and this is my first time doing a dequeue and the book I'm reading doesn't help much.

I'm just a little lost and double seems more complicated than single.

EDIT

Single Queue Code:

public class ListQueue<AnyType> implements Queue<AnyType>
{
    private ListNode<AnyType> front;
    private ListNode<AnyType> back;
    private int counter;

    public ListQueue( )
    {
        front = back = null;
    }

    public boolean isEmpty( )
    {
        return front == null;
    }

    public void enqueue( AnyType x )
    {
        if( isEmpty( ) )    // Make queue of one element
            back = front = new ListNode<AnyType>( x );
        else                // Regular case
            back = back.next = new ListNode<AnyType>( x );
        counter++;
    }

    public AnyType dequeue( )
    {
        if( isEmpty( ) )
            throw new UnderflowException( "ListQueue dequeue" );

        AnyType returnValue = front.element;
        front = front.next;
        counter--;
        return returnValue;
    }

    public AnyType getFront( ) 
    {
        if( isEmpty( ) )
            throw new UnderflowException( "ListQueue getFront" );
        return front.element;
    }

    public void makeEmpty( )
    {
        front = null;
        back = null;
        counter = 0;
    }
}

There it is

EDIT

Here is the ListNode class

class ListNode<AnyType>
{

    public ListNode( AnyType theElement )
    {
        this( theElement, null );
    }

    public ListNode( AnyType theElement, ListNode<AnyType> n )
    {
        element = theElement;
        next    = n;
    }

    public AnyType   element;
    public ListNode<AnyType> next;
}


With a double-ended queue, you keep two references, one to the next element and one to the previous element.

Start from the single-ended queue and add the backwards references.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号