Как написать метод добавления / вставки с DoublyLinkedList в Java - PullRequest
0 голосов
/ 20 марта 2019

Мне нужна помощь с моим методом добавления в Java. Работает с DoublyLinked List.

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

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

Вот мой код ниже:

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(index < 0)
    {
        throw new IndexOutOfBoundsException();
    }
    if(index > size)
    {
        throw new IndexOutOfBoundsException();
    }
    if (first.data == null)
    {
        throw new NullPointerException();
    }
    if (index == 0)
    {
        first = new Node(value, null, null);
        first.next = first;
        first.prev = first;
    }
    else
        {
        Node current = first;
        for (int i = 0; i < index; i++)
        {
            current = current.next;
        }
        current.prev.next = new Node(value, current, current.prev); // This is the line where I get lost on. 
        current.prev = current.prev.next;
    }
    size++;
}

Остальная часть моего кода здесь. Пожалуйста, сосредоточьтесь на методе, над которым я работаю. благодарю вас!

@SuppressWarnings("unchecked")
public void remove(int index)
{
    if(index < 0)
    {
        throw new IndexOutOfBoundsException();
    }
    if(index > size)
    {
        throw new IndexOutOfBoundsException();
    }
    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; i++)
        {
            current = current.next;
        }
           // current.prev = current.next;
            current.next = current.next.next;
    }
    size--;
}
@SuppressWarnings("unchecked")
public E get(int index)
{
    if(index < 0)
    {
        throw new IndexOutOfBoundsException();
    }
    if(index > size)
    {
        throw new IndexOutOfBoundsException();
    }
    Node current = first;
    for (int i = 0; i < index; i++)
    {
        current = current.next;
    }
    return (E) current.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;
}
@SuppressWarnings("unchecked")
public String toString()
{
    if (isEmpty())
    {
        return "[]";
    }
    else
        {
            String result = "[" + first.data;
            Node current = first.next;
        for(int i = 0; i < size-1; i++)
        {
            result += ", " + current.data;
            current = current.next;
        }
        result += "]";
        return result;
    }
}
}

1 Ответ

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

Это было нелегко, но я разобрался с ответом на свой вопрос.

 @SuppressWarnings("unchecked")
 public void add(int index, E value)
 {
    if(index > size || index < 0)
    {
        throw new IndexOutOfBoundsException();
    }
    if (first == null)
    {
        Node n = new Node(value, null, null);
        n.next = n;
        n.prev = n;
        first = n;
    }
    else
        {
        Node current = first;
        for (int i = 0; i < index; i++)
        {
            current = current.next;
        }
        //current points to node that will follow new node.
        Node n2 = new Node(value, current, current.prev);
        current.prev.next = n2;
        current.prev = n2;
        //update first if necessary.
        if(index == 0)
        {
            first = n2;
        }
    }
    size++;
}
...