从数组列表创建链表

问题描述 投票:0回答:1

我的老师希望我们从头开始创建一个链表类,其中一部分是编写一个构造函数,该构造函数采用通用数组列表并将其转换为链表,但我遇到了麻烦。

这是我到目前为止的代码:

public LinkedList(ArrayList<E> list)
    {
        //If the list is null or initialized but empty, set head = null and size = 0.
        head = null;
        size = 0;
        if (list != null && !list.isEmpty())
        {
            //Creating a new Node manually to set the head pointer to.
            head = new Node<E>(list.get(0));
            //The current Node is for iterating through the list.
            Node<E> current = head;
            for (int i = 0; i < list.size(); i++)
            {
                //Creating a new Node that the current Node points to then making current point to the next Node.
                current.next = new Node<E>(list.get(i));
                current = current.next;
            }
            size = list.size();
        }
    }

当我用整数数组(例如 [1, 2, 3])测试它时,代码将创建一个包含 [1, 1, 2] 的链表,我不明白为什么。任何帮助将不胜感激。

java linked-list
1个回答
0
投票

如果你有的话,我建议重复使用

add()
方法:

public LinkedList<E> {

  private int size = 0;
  private Node<E> head = null;
  private Node<E> tail = null;

  public LinkedList(List<E> list) {
    list.forEach(::add)
  }

  public add(E added) {
    if (head == null) {
      head = new Node<E>(added);
      tail = head;
    } else {
      tail.next = new Node<E>(added);
      tail = tail.next;
    }

    size++;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.