Как написать метод удаления с помощью циклического двусвязного списка со стандартными узлами в Java - PullRequest
0 голосов
/ 18 марта 2019

Я реализую циклическую структуру данных DoublyLinkedList. Как в одиночку связанный список, узлы в двусвязном списке имеют ссылку на следующий узел, но в отличие от односвязного списка, узлы в двусвязном списке также имеют ссылку на предыдущий узел. Кроме того, поскольку список «циклический», ссылка «следующий» в последнем узле в списке указывает на первый узел в списке, а ссылка «предыдущая» в первом узле в списке указывает на последний узел в список.

У меня проблемы с моим методом удаления из-за некоторого размера. Это сообщение я получаю, когда запускаю тесты.

Вот мой код:

public class DoublyLinkedList<E>
{
private Node first;
private int size;

@SuppressWarnings("unchecked")
public void add(E value)
{
    if (first == null)
    {
        first = new Node(value, null, null);
        first.next = first;
        first.prev = first;
    }
    else
        {
        first.prev.next = new Node(value, first, first.prev);
        first.prev = first.prev.next;
    }
    size++;
}
private class Node<E>
{
    private E data;
    private Node next;
    private Node prev;

    public Node(E data, Node next, Node prev)
    {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }
}
@SuppressWarnings("unchecked")
public void add(int index, E value)
{
    if (first.data == null)
    {
        throw new IndexOutOfBoundsException();
    } else if (index == 0)
    {
        first = new Node(value, first.next, first.prev);
    }
    else
        {
        Node current = first;
        for (int i = 0; i < index - 1; i++)
        {
            current = current.next;
        }
        current.next = new Node(value, current.next, current.prev);
    }
}

Вот метод, с которым мне нужна помощь. Метод remove должен удалить элемент по указанному индексу в списке. Обязательно рассмотрите случай, когда список пуст и / или удаленный элемент является первым в списке. Если параметр индекса недействителен, должно быть выдано исключение IndexOutOfBoundsException.

@SuppressWarnings("unchecked")
public void remove(int index)
{
    if (first.data == null)
    {
        throw new IndexOutOfBoundsException();
    }
    else if (index == 0)
    {
        first = first.next;
    }
    else
        {
            Node current = first.next;
            for (int i = 0; i < index - 1; i++)
        {
            current = current.next;
        }--size;
            current.next = current.next.next;

    }
}

Вот остаток кода. Метод get неверен, но я спросил об этом в другом вопросе.

    public E get(int index)
    {
   if(index >= size)
    {

    }
    return null;
    //return first.data;
}
@SuppressWarnings("unchecked")
public int indexOf(E value)
{
    int index = 0;
    Node current = first;
    while (current != current.next)
    {
        if (current.data.equals(value))
        {
            return index;
        }
        index++;
        current = current.next;
    }
    return index;
}
public boolean isEmpty()
{
    if (size == 0)
    {
        return true;
    }
    else
        {
        return false;
    }
}
public int size()
{
    return size;
}

1 Ответ

0 голосов
/ 21 марта 2019

Это было непросто, однако я нашел ответ на свой вопрос. Это циклический двусвязный список. Вот оно:

 @SuppressWarnings("unchecked")
 public void remove(int index)
 {
    if(index < 0 || index > size)
    {
        throw new IndexOutOfBoundsException();
    }
    Node n = first;
    for(int i = 0; i < index; i++)
    {
        n = n.next;
    }
    // n points to node to remove
    n.prev.next = n.next;
    n.next.prev = n.prev;
    if (index == 0)
    {
        if(size == 1)
        {
            first = null;
        }
        else
        {
            first = first.next;
        }
    }
    size--;
}
...