使用 treeSet 中的元素初始化链表

Initializing linked list with elements in a treeSet

问题是这样的: 定义一个以 TreeSet 作为参数的构造函数,并用集合中的元素初始化一个链表。新列表必须按字典顺序递增排序。

此方法将使用下面的 class 来实现:

public class LinkedList<T extends Comparable<T>> {
    private class Node{
        private T data;
        private Node next;

        private Node(T data){
            this.data = data;
            next = null;
        }

    }

    private Node head;

    public LinkedList(){
        head = null;
    }

现在我知道 TreeSet 本质上是排序的,所以我在这里真正需要做的就是从 TreeSet 中取出元素并将其放在这个链表的前面。但是我在从集合中检索元素并将其添加到 LinkedList 时遇到了问题。我写了一个私人助手 add(T data) 方法并正在使用它,但我不知道这是否是我应该采用的方法。我是数据结构的新手,所以对集合及其实现知之甚少。

public class LinkedList<T extends Comparable<T>> {
    private class Node{
        private T data;
        private Node next;

        private Node(T data){
            this.data = data;
            next = null;
        }

    }

    private Node head;

    public LinkedList(){
        head = null;
    }

    public void add(T data){
        Node n = new Node(data);
        if(head == null){
            head = n;
        }
        else{
            n.next = head;
            head = n;
        }
    }

    public LinkedList(TreeSet<T> test){
        Iterator<T> itr = test.iterator();
        while(itr.hasNext()){
            this.add(itr.next());
        }
    }

您要解决的主要问题是您需要将每个项目添加到列表的末尾而不是开头。

将节点添加到列表的开头很容易:

public void addToHead(T data) {
    Node node = new Node(data);
    node.next = head;
    head = node;
}

添加到末尾比较困难,因为您没有对尾部的引用。但解决方案相当简单:在您正在开发的构造函数中,保留对列表尾部的引用,以便您可以在链接的末尾而不是开头添加每个值。

问题包括"increasing lexicographic order."

我的解决方案没有辅助方法:

    public LinkedList(TreeSet<T> test){
        Node currNode = null;
        for(T data : test) {
            Node newNode = new Node(data);
            if(head == null) {
               head = newNode;
               currNode = head;
            }
            else {
               currNode.next = newNode;
               currNode = currNode.next;
            }

        }
    }