简体   繁体   中英

How do I write an addElement method to a sorted LinkedList?

I have an assignment that goes:

implement a linked list of String objects by use of the class Node (see Big >Java Early Objects 16.1.1). Write methods, that make it possible to insert >and delete objects, as well as print all objects in the list. It is a >requirement that all elements in the list are sorted, at all times, according >to the natural ordering of Strings(Comparable).

The method that I can't seem to get right, is the addElement method

The entire class is here: https://pastebin.com/Swwn8ykZ And the mainApp: https://pastebin.com/A22MFDQk

I've looked through the book (Big Java Early Objects), as well as looked on geeksforgeeks

public void addElement(String e) {
    Node newNode = new Node();
    if (first.data == null) {
        first.data = e;
        System.out.println("Success! " + e + " has been 
added!");
    } else if (first.data.compareTo(e) == 0) {
        System.out.println("The element already exists in the 
list");
    } else {
        while (first.next != null) {
            if (first.next.data.compareTo(e) != 0) {
                first.next.data = e;
            } else {
                first.next = first.next.next;
            }
        }
    }
}

public static void main(String[] args) {
    SortedLinkedList list = new SortedLinkedList();

    String e1 = new String("albert");
    String e2 = new String("david");
    String e3 = new String("george");
    String e4 = new String("jannick");
    String e5 = new String("michael");

    // ----------------SINGLE LIST--------------------------
    list.addElement(e1);
    list.addElement(e2);
    list.addElement(e3);
    list.addElement(e4);
    list.addElement(e5);

    System.out.println("Should print elements after this:");
    list.udskrivElements();
 }
}

Expected result: The five names printed in a list

Actual result: The first name printed

Given this Node class:

private class Node {
    public String data;
    public Node next;
}

and a class-level field of private Node first; that is initially null to signal an empty list, the addElement could be like this:

public void addElement(String text) {
    if (text == null) return; // don't store null values

    Node extra = new Node();
    extra.data = text;

    if (first == null) {
        // no list yet, so create first element
        first = extra;
    } else {
        Node prev = null; // the "previous" node
        Node curr = first; // the "current" node

        while (curr != null && curr.data.compareTo(text) < 0) {
            prev = curr;
            curr = curr.next;
        }

        if (curr == null) {
            // went past end of list, so append
            prev.next = extra;
        } else if (curr.data.compareTo(text) == 0) {
            System.out.println("Already have a " + text);
        } else {
            // between prev and curr, or before the start
            extra.next = curr;
            if (prev != null) {
                prev.next = extra;
            } else {
                // append before start, so 'first' changes
                first = extra;
            }
        }
    }
}

By the way, also try and add the names in an unsorted order to check that the list sorts them (I found a bug in my code when I tried that).

Define a Node like this :

class Node 
{ 
       int data; 
       Node next; 
} 

Below method will insert element into Sorted order :

void sortInsert(Node new_node){
    Node current; 
    if (head == null || head.data >= new_node.data) 
    { 
        new_node.next = head; 
        head = new_node; 
    } 
    else { 
           current = head; 
           while ( current.next.data < new_node.data && current.next != null)
            current = current.next; 
     new_node.next=current.next;
     current.next=new_node;

    } 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM