How would I make my custom generic type linked list in Java sorted?

后端 未结 3 1839
温柔的废话
温柔的废话 2021-01-24 23:44

I am writing my own linked list in java that is of generic type instead of using the java collections linked list. The add method for the linked list is made up of the followi

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 00:07

    You mention using generics but then mention sorting them alphabetically. Generics are not necessarily character strings, they are used to represent any type, while a sort property like alphabetically implies alphabetic characters. My Answer assumes you are expecting generic objects of type T which have an alphabetic nature to them. In my example I exclusively use a String

    You can set you code up to search for the position to add itself instead of providing it.

    public void add(T item) {
        Node addThis = new Node(item);
        Node itr = head;
    
        while (itr.hasNext()) {
            if (addThis.compareTo(itr.getNext()) <= 0) { // itr > addThis
                addThis.setNext(itr.getNext());
                itr.setNext(addThis);
                return;
            }
            itr = itr.getNext();
        }
        addThis.setNext(null);
        itr.setNext(addThis);
        return;
    } // end add
    

    Then in your Node class, you can implement the Interface Comparable . I'm assuming you store a string since you asked about alphabetizing. This Question Explains comparing strings alphabetically.

    class Node implements Comparable {
    
    
        String value;  // ASSUMING YOU ARE USING A STRING AS YOUR GENERIC TYPE T
    
        @Override
        public int compareTo(Node otherNode) {
            int i;
            String thisString = this.getValue();
            String otherString = otherNode.getValue();
            int minSize = ( otherString.length() > thisString.length() ? thisString.length() : otherString.length() );
            for (i = 0; i < minSize; i++) {
                 if (thisString.charAt(i) > otherString.charAt(i)) {
                     return 1;
                 } else if (thisString.charAt(i) < otherString.charAt(i)) {
                     return -1;
                 }
            }
            if (otherString.length() > thisString.length()) {
                return 1;
            } else if (otherString.length() < thisString.length()) {
                return -1;
            } else {
                return 0;
            }
        }
    
        // OTHER CLASS CONSTRUCTORS, VARIABLES, AND METHODS
    }
    

    In order to do this with simply generics, you would need to implement you Node class with the type T implementing Comparable like so:

    class NodeNode> implements Comparable {
    
    
        T value;
    
        @Override
        public int compareTo(Node otherNode) {
            return this.getValue().compareTo(otherNode.getValue());
        }
    
        // OTHER CLASS CONSTRUCTORS, VARIABLES, AND METHODS
    }
    

提交回复
热议问题