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

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

如何在Java的參數中使用索引的遞歸創建刪除方法?

如何在Java的參數中使用索引的遞歸創建刪除方法?

揚帆大魚 2022-09-14 10:30:24
我在如何啟動此方法時遇到問題。我正在嘗試使用代碼中的遞歸創建一個 remove 方法。基本上我有一個公共和私人的刪除方法。remove(int) 方法(公共)應刪除列表中指定索引處的元素。我需要解決列表為空和/或刪除的元素是列表中第一個元素的情況。如果索引參數無效,則應引發“索引超出邊界異?!?。為了允許遞歸實現,此方法應解決特殊情況并委托刪除(int,int,Node)以進行遞歸。下面是類:public class SortedLinkedList<E extends Comparable<E>>{    private Node first;    private int size;    // ...}代碼如下:public void remove(int index){    if(index < 0 || index > size)    {        throw new IndexOutOfBoundsException();    }    remove(index++, 0, first);    if (index == 0)    {        if(size == 1)        {            first = null;        }        else        {            first = first.next;        }    }    size--;}和私有方法:private void remove(int index, int currentIndex, Node n){    if(index == currentIndex)    {        remove(index, currentIndex, n.next);    }    remove(index, currentIndex, n.next.next);}私人課程:private class Node{    private E data;    private Node next;    public Node(E data, Node next)    {        this.data = data;        this.next = next;    }}
查看完整描述

1 回答

?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

返回void

使用兩個索引

private void remove(int index, int current, Node n) {

  if (n == null || index <= 0 || (index == 1 && n.next == null) {

    throw new IndexOutOfBoundsException();

  }

  if (current == index - 1) {

    // Remove 'n.next'.

    n.next = n.next.next; 

  } else {

    remove(index, current + 1, n.next);

  }

}

用法

public void remove(int index) {

  if (first == null || index < 0) {

    throw new IndexOutOfBoundsException();

  }

  if (index == 0) {

    // Remove 'first'.

    first = first.next;

  } else {

    remove(index, 0, first);

  }

  size--;

}

使用一個索引

只需要一個索引:


private void remove(int index, Node n) {

  if (n == null || index <= 0 || (index == 1 && n.next == null) {

    throw new IndexOutOfBoundsException();

  }

  if (index == 1) {

    // Remove 'n.next'.

    n.next = n.next.next; 

  } else {

    remove(index - 1, n.next);

  }

}

用法

public void remove(int index) {

  if (first == null || index < 0) {

    throw new IndexOutOfBoundsException();

  }

  if (index == 0) {

    // Remove 'first'.

    first = first.next;

  } else {

    remove(index, first);

  }

  size--;

}

返回Node

更好的是返回而不是:Nodevoid


private Node remove(int index, Node n) {

  if (n == null || index < 0) {

    throw new IndexOutOfBoundsException();

  }

  if (index == 0) {

    // Remove 'n' and return the rest of the list.

    return n.next; 

  }

  // 'n' stays. Update the rest of the list and return it.

  n.next = remove(index - 1, n.next);

  return n;

}

用法

public void remove(int index) {

  first = remove(index, first);

  size--;

}


查看完整回答
反對 回復 2022-09-14
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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