Deque JAVA中的removeLast / addFirst方法

时间:2016-02-26 18:48:07

标签: java stack queue deque

我需要帮助来解决我的removeLastaddFirst方法。

我想不出一种方法可以将一个元素添加到队列的头部,并将头部指向该元素,因为我只能访问head.element / head.next

同样,在删除最后一个对象后,我找不到引用队列尾部的方法,因为我被限制为queue.elementqueue.next

任何帮助将不胜感激!

public class DequeImpl implements Deque{

    private Node head;
    private Node tail;
    private int size;

    public DequeImpl(){
        head=null;
        tail=null;
        size=0;
    }

    //This is a toString
    public String toString(){
        String toSend = "";
        Node baladeur = head;
        while(baladeur != null) {
            toSend += " " + baladeur.element;
            baladeur = baladeur.next;
        }
        return toSend;
    }

    // renvoie true if empty
    public boolean isEmpty(){
        return size==0;
    }


    public int size(){
        return this.size;
    }

   //To complete ///////
    public void addFirst(Object element){
        Node element2 = new Node(element, head);
        if(isEmpty()){
            head=tail=element2;
        }
        else{

        }
        size++;
    }

    public void addLast(Object element){
        Node element3 = new Node(element, null);
        if(isEmpty()){
            head=tail=element3;
        }
        else{
            tail.next=element3;
            tail = tail.suivant;
        }
        size++;
    }

    public Object removeFirst() throws QueueEmptyException{
        if(isEmpty())throw new QueueEmptyException("");
        Object element4 = head.element;
        if(size==1){
            head=tail=null;
        }
        else{
            head=head.next;
        }
            size--;
        return element4;
    }

   //To complete ///////

    public Object removeLast()throws QueueEmptyException{
        if(isEmpty())throw new QueueEmptyException("");
        Object element5 = tail.element;
        if(size==1){
            head=tail=null;
        }
        else{
            tail.next=null;
        }
        return null;
    }

    public Object first()throws QueueEmptyException{
        if(isEmpty())throw new QueueEmptyException("");
        return head.element;

    }

    public Object last()throws QueueEmptyException{
        if(isEmpty())throw new QueueEmptyException("");
        return tail.element;
    }


    private class Node{
        private Object element;
        private Node next;

        private Node(Object element, Node next){
            this.element = element;
            this.next = next;
        }

    }
} 

1 个答案:

答案 0 :(得分:1)

重新分配head非常简单:

Node newHead = ... whatever you do here
newHead.next = head;
head = newHead;
但是,我觉得你的尾巴很痛苦。如果你没有来自tail的后退指针,你所能做的就是遍历整个列表,并且:

if (tail.equals(thisNode.next)) {
  thisNode.next = null;
  tail = thisNode;
  break;
}

更多上下文显示您可以遍历整个列表:

Node thisNode = head;
while (thisNode != null) {
  if (tail.equals(thisNode.next)) {
    thisNode.next = null;
    tail = thisNode;
    break;
  }
  thisNode = thisNode.next;
}