簡體   English   中英

如何在java中刪除鏈表的最后一個節點?

[英]How can I remove the last node of a Linked List in java?

我需要在 Java 中實現 LinkedList 的兩個方法 removeFirst 和 removeLast

第一種方法我是這樣解決的:

@Override
public E removeFirst() {
    if(isEmpty()){
        throw new NoSuchElementException();
    }
    E element = top.next.data;
    top.next = top.next.next;
    numElements--;
    return element;
}

我在使用 removeLast 方法時遇到問題

     public E removeLast() {
     if(isEmpty()){
         throw new NoSuchElementException();
     }

      for (int i = 0; i < numElements;i++) {


      }

}

我的想法是使用 for 循環來查找最后一個元素,但我不知道在那之后該怎么做

有什么建議?

我的節點類如下:

public class Node<E> {

E data;
Node<E> next; 

public Node(E data) {
    this(data,null);
}

public Node(E data, Node<E> next) {
    this.data = data;
    this.next = null;
}

@Override
public String toString () {
    return data.toString();


}

}

這個邏輯應該有效 -

Node <E> tmp;
tmp = next;


while(tmp.next.next != null)
tmp = tmp.next;
tmp.setNext(null);

所以如果我們有 1->3->4->null

每當它達到 3 時,它將 setNext 為 null,因此新數組將如下所示 1->3->null

removeFirstremoveLast已存在於LinkedList類 ( LinkedList javadoc ) 中。 無需從頭開始創建它們。

像這樣的事情可能會起作用,如果沒有看到您的列表類很難說,因為我無法測試它:

  public E removeLast() {
    if(isEmpty()){
        throw new NoSuchElementException();
    }
    Node<E> node = top;
    while (true) {
      Node<E> nextNode = node.next;
      if (nextNode.next == null) {
        node.next = null;
        return nextNode.data;
      } else {
        node = nextNode;
      }
    }
  }

但值得添加的是,通常在單鏈表中,您希望包含類保留尾指針(否則您無法有效地附加到末尾)。 如果你這樣做,你也需要更新你的尾巴。

還有一條評論,如果您發現自己經常刪除最后一個,您想切換到雙向鏈表……為什么不只使用內置的 java.util.LinkedList 類? 這是用於學校項目還是什么?

我們必須保持兩個指針之前和當前。 由於我們記錄了列表中元素的數量,我們可以使用 for 循環遍歷列表並找到 currentNode 指針指向的最后一個節點和 previousNode 指針指向的前一個節點。 最后,將上一個 next 指針更新為 null 並返回 currentNode 數據。

 public E removeLast() {
    if(isEmpty()){
        throw new NoSuchElementException();
    }
    Node previousNode = top;
    Node currentNode = top;
    for (int i = 0; i < numElements -1 ;i++) {
        previousNode = currentNode;
        currentNode = currentNode.next;
    }
    // removed the last element and return the data
    previousNode.next = null;
    numElements-- 
    return currentNode.data;

}

public node removelast() {
    if(isEmpty())
        return null;
    node temp =head;
    node temp2 =head.getNext();
    while(temp!=null && temp2!=null) {
        if(temp2.getNext()==null) {
            tail=temp;
            temp.setNext(null);
        }
        temp2=temp2.getNext();
        temp=temp.getNext();
    }   
    if(head.getNext()==null)
        tail=head;
    return tail;
}

暫無
暫無

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

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