亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java - 從LinkedList中刪除元素,除了第一個

Java - 從LinkedList中刪除元素,除了第一個

慕絲7291255 2022-08-03 15:47:16
我是Java的新手。我創建了一個方法,它將從LinkedList中刪除除第一個元素之外的元素。這個想法是,如果LinkedList的元素數據(以整數為單位)與參數匹配,則布爾值將設置為true。一旦布爾值設置為 true,它將刪除也與初始元素匹配的任何元素?,F在來看看問題。例如,如果我要從此LinkedList中刪除5個,除了第一個:5 5 5 6 5 7 8 9我會得到這樣的結果:5 5 6 7 8 9如您所見,它沒有刪除第二個位置上的5。我的代碼有什么問題嗎?順便說一下,這是代碼public void append(int data) {    Node newNode = new Node(data);    if (head == null) {        head = new Node(data);        return;    }    Node lastNode = head;    while (lastNode.next != null) {        lastNode = lastNode.next;    }    lastNode.next = newNode;    return;}public void insert(int data) {    Node newData = new Node(data);    newData.next = head;    head = newData;}public void removeExceptFirst(int dataValue) { //The mentioned method    boolean duplicate = false;    Node currentNode = head;    while (currentNode.next != null) {        int value = currentNode.next.data;        if (value == dataValue) {            if (!duplicate) {                duplicate = true;                currentNode = currentNode.next;            } else {                currentNode.next = currentNode.next.next;            }        } else {        currentNode = currentNode.next;        }    }    return;}
查看完整描述

3 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

這里的問題是


if (!duplicate) {

     duplicate = true;

     currentNode = currentNode.next;

您正在將replicate = true標記為true并立即分配“currentNode = currentNode.next;”,由于此引用正在保留下一個節點,因此


1. Put the condition outside of the loop to check whether the head element itself is 

   that node, if->yes mark isDuplicate = true and proceed in the loop.

2. Inside the loop check afterward and then assign the next node.

希望這應該有效


查看完整回答
反對 回復 2022-08-03
?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

您跳過了頭節點。嘗試替換

    Node currentNode = head;

    Node currentNode = new Node();
    currentNode.next = head;


查看完整回答
反對 回復 2022-08-03
?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

刪除節點后,應更新當前節點引用以及頭>下一個節點應指向當前節點。請嘗試以下代碼:


if (!duplicate) {

    duplicate = true;

    currentNode = currentNode.next;

     head.next= currentNode.next;

}else {

    currentNode.next = currentNode.next.next;

    currentNode = currentNode.next;

    head.next = currentNode;  }

`


查看完整回答
反對 回復 2022-08-03
  • 3 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號