簡體   English   中英

在列表尾部插入元素時出現問題 JAVA

[英]Problems inserting element at the tail of a list JAVA

我的任務是將 linkedList 實現為隊列。 我在列表尾部添加元素時遇到問題。 我沒有異常,但問題是添加元素時,列表之后仍然是空的,我真的沒有看到問題。 誰有解決辦法? :)

@Override
public void add(E element) {
        if(element == null){
            throw new NullPointerException();
        }else{
            this.addNodeLastInQueue(element); 
        }
    
}


public void addNodeLastInQueue(E element){
    
        MyNode<E> nodeToBeAdded = new MyNode<E>(element);  
        if(isEmpty()){
            head = nodeToBeAdded;
            tail = nodeToBeAdded;//Osäker om denna behövs
        }else{
            tail.setNext(nodeToBeAdded);   
            tail = nodeToBeAdded;
        }  
    }

我已經嘗試了我想出的一切

根據定義,當您在隊列中添加一個元素時,它會自動添加到列表的末尾(請參閱 FIFO),因此您無需調用方法“addNodeLastInQueue”。 最佳做法是將其稱為“排隊”。

這里的方法:

public void enqueue(E element) {
    Node<E> oldlast = last;
    last = new Node<E>();
    last.e = e; // It refers to the "e" attribute in static class
    last.next = null;
    if (isEmpty()) first = last;
    else           oldlast.next = last;
    n++;
}

提示:我建議你實現一個輔助鏈表 static class 以便為隊列提供節點屬性。 事實上,我在我的方法中使用它。

// helper linked list class
private static class Node<E> {
    private E e;
    private Node<E> next;
}

我希望我有所幫助。 再見!

public class MyNode<E> {

        private E data;
        private MyNode <E> next;
  
        public MyNode(E data) {
           this.data = data;
           this.next = null; 
        }  
    }

public void enQueue(E element) {
        MyNode<E> oldTail = tail;
        tail = new MyNode<E>(element);
        tail.data = element; 
        tail.next = null;
        if (isEmpty()) head = tail;
        else           oldTail.next = tail;
    }


@Override
public void add(E element) {
    if(element == null){
        throw new NullPointerException();
    }else{
        this.enQueue(element); 
    }
    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM