2014-11-10 1 views
0

Я реализую метод remove() настраиваемого класса LinkedList, но он не удаляет какие-либо элементы из списка, и я не могу понять, почему.Пользовательский LinkedList: метод удаления не работает должным образом

Вот как я это делаю:

public void remove(int position) { 
     if (position < 0 || position >= size) { 
      throw new IndexOutOfBoundsException(
        "position should be beween 0 and size - 1"); 
     } 

     Cell current = top; 
     for (int i = 0; i < position; i++) { 
      current = current.next; 
     } 
     current = current.next.next; 
     size--; 
} 

Этот метод пытается удалить элемент между 2 узлами (удаление первого узла и последние случаи узла игнорируются).

Это тест я выполняется, и после попытки удалить элемент с индексом 2, он по-прежнему печатает список отверстий:

CustomList<String> list = new CustomList<String>(); 
list.add("Hello"); 
list.add("morena"); 
list.add("What"); 
list.add("Miranda"); 
list.add("Aston");  

list.remove(2); 

list.printAll(); 

Для завершения, здесь полное осуществление списка:

public class CustomList<T> { 

    private class Cell { 
     T data; 
     Cell next; 

     public Cell(T data) { 
      this.data = data; 
     } 
    } 

    private Cell top; 
    private int size; 

    public void add(T data) { 
     addAtEndInOn(data); 
     size++; 
    } 

    /** 
    * adds an item at the end of the list in O(n) by iterating the whole list 
    * before adding the node 
    */ 
    private void addAtEndInOn(T data) { 
     if (top == null) { 
      top = new Cell(data); 
     } else { 
      Cell current = top; 
      while (current.next != null) { 
       current = current.next; 
      } 
      current.next = new Cell(data); 
     } 
    } 

    public void remove(int position) { 
     if (position < 0 || position >= size) { 
      throw new IllegalArgumentException(
        "position should be a positive number"); 
     } 

     Cell current = top; 
     for (int i = 0; i < position; i++) { 
      current = current.next; 
     } 
     current = current.next.next; 
     size--; 
    } 

    public void printAll() { 
     Cell current = top; 
     while (current != null) { 
      System.out.println(current.data); 
      current = current.next; 
     } 
    } 
} 

ответ

2

current = current.next.next ничего не внесет в ваш список.

Для того, чтобы удалить элемент, вам нужно написать:

current.next = current.next.next; 

Это устранило бы элемент, который находится рядом с текущим элементом. Это не тот элемент, который вы хотели удалить, вы должны изменить цикл for так, чтобы он останавливался, когда current является элементом до того, который вы хотите удалить.

Обязательно проверьте, что current.next не является нулевым, чтобы избежать NullPointerException.

2

You have to break the link, not just change the position of current

Вы должны разорвать связь, а не просто изменить положение тока. Ссылка представлена ​​current.next

Смежные вопросы