I need to create a LinkedList out of the given strings and as I am adding them sort the entries alphabetically and get rid of duplicates. I got it to not add duplicate strings but I can't figure out add them in order as I go.
Here is my code for the Node.
package nodes; public class Node { private String data; // The data stored in this node private LinkedNode next; // private Node next; //The next node in the data structure public Node () { this ( null, null ) ; } public Node ( String newData, Node newNext ) { data = newData; next = newNext; } public String getData () { return data; } public Node getNext () { return next; } public void setData ( String newData ) { data = newData; } public void setNext (Node newNext) { next = newNext; } } // LinkedNode
And the LinkedList
package nodes; public class ListLL { protected Node top; // The first node in the list protected Node tail; // The last node in the list public ListLL() { top = null; tail = null; } public void addInorder(String s) { Node temp = new Node(s, null); Node current = top; if (top == null) { top = temp; return; } if (current.getData().equals(s)) { return; } while (current.getNext() != null) { current = current.getNext(); if (current.getData().equals(s)) { return; } } temp.setNext(current.getNext()); current.setNext(temp); } public void display() { Node temp = top; while (temp != null) { System.out.println(temp.getData()); temp = temp.getNext(); } } public void displayUseTail() { Node temp = top; while (temp != tail.getNext()) { System.out.println(temp.getData()); temp = temp.getNext(); } } public static void main(String[] args) { ListLL list = new ListLL(); list.addInorder("banana"); list.addInorder("banana"); list.addInorder("orange"); list.addInorder("pear"); list.addInorder("apple"); list.addInorder("grape"); list.addInorder("grape"); list.addInorder("pear"); list.addInorder("grape"); list.addInorder("banana"); list.addInorder("berry"); list.addInorder("strawberry"); list.addInorder("melon"); list.display(); //list.displayUseTail(); } }
Thank you for your help!