简体   繁体   中英

Java LinkedList adding multiple nodes

my question is in my main method, how to add multiple nodes to the linked list....What I have now with first, node2, node3..I thought was adding those nodes but I realized I don't think I'm actually doing anything with those nodes and their values, right? How do I use setData() and setNext() to add all of those nodes. Does that make sense?

ListNode<String> node4 = new ListNode<String>("Fourth", null);
ListNode<String> node3 = new ListNode<String>("Third", node4);
ListNode<String> node2 = new ListNode<String>("Second", node3);
ListNode<String> first = new ListNode<String>("First", node2);

If the above sets up the values how do I add them all?

Do I then need to set the data and next for each one of these? (This seems redundant since I seem to be setting up the value of each nodes data and next in the constructor above?)

first.setData("first");
first.setNext(node2); 
node2.setData("Second");
node2.setNext(node2);
//.....

I'm trying to add all of the above nodes so I can test my addLast() method by adding a new node. However, when I call my addLast() method in main as you can see below the only thing that's printed is that addLast() value I added (and first if I call addFirst()).

Test Class

public class LinkedListDriver
{

    public static void main(String[] args) {
        //List<String> list = new LinkedList<String>();                   //comment out this line to test your code
        SinglyLinkedList<String> list = new SinglyLinkedList<String>(); //remove comment to test your code

        ListNode<String> node4 = new ListNode<String>("Fourth", null);
        ListNode<String> node3 = new ListNode<String>("Third", node4);
        ListNode<String> node2 = new ListNode<String>("Second", node3);
        ListNode<String> first = new ListNode<String>("First", node2);

        ListNode value = new ListNode("First", new ListNode("Second", new ListNode("Third", null)));

        //I've been messing around with this but 
        list.addFirst(first.getData());
        list.addFirst("Second");

        list.addLast("Fifth");
        list.printList();
    }
}

I didn't add my other two classes because I didn't think it was relevant but if you'd like to see it let me know. I'm very new this is only my second class and it's online and is poorly constructed class, please be nice lol

SinglyLinkedList class

//This class implements a very simple singly-linked list of Objects
public class SinglyLinkedList<E>
{
    ListNode<E> first; // first element

    public SinglyLinkedList() {
        first = null;
    }

    public E getFirst() {
        if (first == null) {
            throw new NoSuchElementException();
        } else
            return first.getData();
    }

    public void addFirst(E value) {
        first = new ListNode<E>(value, first);
    }

    // Methods below implemented by you. Note: while writing methods, keep in mind
    // that you might be able to call other methods in this class to help you - you
    // don't always need to start from scratch(but you'll have to recognize when)

    public void addLast(E value) {
        ListNode<E> temp = first;
        //If list is empty make new node the first node.
        if (temp == null) {
            first = new ListNode <E>(value, null);
            first.setNext(null);
        }//Otherwise loop to end of list and add new node.
        else {
            while (temp.getNext() != null) {
                temp = temp.getNext();
            }
            temp.setNext(new ListNode<E>(value, null));
        }
    }//end addLast

    // throws an exception - you decide when and which one

    public E getLast() {
        ListNode<E> temp = first;
        if (temp == null) {
            throw new NullPointerException("There are no elements in this list to get.");
        } else {
            while (temp.getNext() != null) {
                temp = temp.getNext();
            }
            return temp.getData();
        }
    }

    // throws an exception - you decide when and which one

    public E removeFirst() {
        if (first == null) {
            throw new NullPointerException("There are no elements in this list to remove.");
        }
        ListNode<E> tempRemove = first;
        return null; //just so it'll compile
    }

    // throws an exception - you decide when and which one

    public E removeLast() {
        return null; //just so it'll compile
    }

    // return the number of elements in the list

    public int size() {
        return 0; //just so it'll compile
    }

    // return true if o is in this list, otherwise false

    public boolean contains(E obj) {
        return true; //just so it'll compile
    }

    public void printList(java.io.PrintStream out) {
        if (first == null) {
            System.out.println("The list is empty");
        }
        ListNode<E> current = first;
        while (current != null) {
            System.out.println(current.toString());
            current = current.getNext();
        }
    }

    public String toString() {
        String s = "[";
        ListNode<E> current = first;
        //write code to traverse the list, adding each object on its own line
        while (current.getNext() != null) {
            current = current.getNext();
        }

        s += "]";
        return s;
    }

    // OPTIONAL: just for fun...and a challenge

    public void reverse() {
    }
}

ListNode class is your basic getNext setNext, getData setData....

A couple of points, mostly summarizing the comments:

You shouldn't work with ListNode objects in main() at all - that should be the job of the SinglyLinkedList class. ListNode doesn't even need to be visible to the rest of the code, it could be a nested class in SinglyLinkedList . You should only be exchanging the data objects (Strings in this case) with SinglyLinkedList .

If you want to test for example the addLast() method, you could start with an empty list and repeatedly call list.addLast() , as Shane mentions in his answer. That way you will make sure it works when the list is empty as well as nonempty.

SinglyLinkedList<String> list = new SinglyLinkedList<String>();
list.addLast("first");
list.addLast("second");
list.addLast("third");
list.printList(System.out);

As for adding multiple nodes in a single call - this linked list doesn't have a method for that. You could add a method for adding all elements of an array for example, but you can just call addLast() sequentially with the same effect. You can create some helper method in the main class to populate the list in this way, if you want to start with some base data for testing other methods.

As a side note: if printList() takes java.io.PrintStream out as argument, you should use it instead of System.out . That is

out.println(...)

instead of

System.out.println(...)

Also, it's better to throw NoSuchElementException rather than NullPointerException as an indication that the requested element doesn't exist.

If you want a convenient way to populate the list, you could have something like this in your main class:

static <E> void addToList(SinglyLinkedList<E> list, E... values) {
    for (E value : values) {
        list.addLast(value);
    }
}

and use it like this:

SinglyLinkedList<String> list = new SinglyLinkedList<String>();
addToList(list, "first", "second", "third");

What are you trying to do? If you're attempting to populate the linked list, all you need to do is continually call list.addLast, which will take a single parameter (the data in the new node you're adding), and deal with creating the new node and placing it in the back of the list.

You shouldn't need to create any nodes in your main, I'm assuming, as they are generally handled entirely by the linkedlist class.

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