Как реализовать toArray () в связанном списке? - PullRequest
0 голосов
/ 13 марта 2019

Я создал отсортированный класс связанного списка, и единственная часть, с которой я борюсь, - это правильная реализация метода toArray ().

    public class SortedLinkedList<T extends Comparable<T>> implements ListInterface<T>
{

  // container class

  private class LinkedNode<T>
  {
    public T data;
    public LinkedNode<T> next;

    public LinkedNode(T data, LinkedNode<T> next)
    {
      this.data = data;
      this.next = next;
    }
  }

  // private variables

  private LinkedNode<T> head, tail;
  private int size;
  private String name;

  // constructor

  public SortedLinkedList(String name)
  {
    head = null;
    tail = null;
    size = 0;
    this.name = name;
  }

  // core functions

  public void Add(T data)
  {
    size++;

    // creation of new node to be added

    LinkedNode<T> newNode = new LinkedNode<T>(data, null);

    // check for empty list; adds node at head if so

    if (head == null)
    {
      head = newNode;
      return;
    } 

    if (head.data.compareTo(data) < 0)
    {
      head = newNode;
      return;
    }

    // insertion in middle

    LinkedNode<T> current = head;
    LinkedNode<T> prev = null;

    while (current != null)
    {
      if (current.data.compareTo(data) > 0)
      {
        prev.next = newNode;
        newNode.next = current;
        return;
      }
      prev = current;
      current = current.next;
      }

    // insertion at end

    prev.next = newNode;

    return;
  }

  public void Remove(T data)
  {
    if (head == null)
    {
      return;
    }

    LinkedNode<T> current = head.next;

    while (current != null && current.next != null)
    {
      if (current.data.compareTo(current.next.data) == 0)
      {
        current.next = current.next.next;
      } else {
      current = current.next;
      }
    }
    size--;
  }

  public int size()
  {
    return size;
  }

  @SuppressWarnings("unchecked")
  public T[] toArray()
  {
    T[] result = (T[])(new Comparable[size()]);

    int counter = 0;

    for ( T item : )
    {
      result[counter++] = item;
    }
    return result;
  }

Проблема, с которой я столкнулся, заключается в том, что я должен включить после "T item:" в моей строке for / каждой строки.В последнее время у меня не было проблем с реализацией аналогичного метода toArray () в классе набора, поскольку это было «для каждого элемента в наборе», но по какой-то причине я не понимаю, что поместить для связанного списка.

Ответы [ 3 ]

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

Попробуйте это.

  @SuppressWarnings("unchecked")
  public T[] toArray()
  {
    T[] result = (T[])(new Comparable[size()]);

    int counter = 0;

    for ( LinkedNode<T> cursor = head; cursor != null; cursor = cursor.next )
    {
      result[counter++] = cursor.data;
    }
    return result;
  }
0 голосов
/ 13 марта 2019

На самом деле, ответ на ваш вопрос this:

@SuppressWarnings("unchecked")
public T[] toArray() {
    T[] result = (T[])(new Comparable[size()]);

    int counter = 0;

    for (T item : this) {
        result[counter++] = item;
    }
    return result;
}

Это правильно, но для этого вам необходимо реализовать интерфейс Iterable<T>:

public class SortedLinkedList<T extends Comparable<T>> implements ListInterface<T>, Iterable<T> {
    @Override
    public Iterator<T> iterator() {
        return null;
    }

    // ...
}
0 голосов
/ 13 марта 2019

Не использовать для цикла с linked-lists. Попробуйте что-то вроде ниже:

LinkedNode cursor = head;
int index = 0;
while (cursor != null ){
  result[index] = cursor.data;
  cursor = cursor.next;
  index++;
}
...