【问题标题】:Java LinkedList adding multiple nodesJava LinkedList添加多个节点
【发布时间】:2016-01-24 08:23:20
【问题描述】:

我的问题是在我的主要方法中,如何将多个节点添加到链表中......我现在首先拥有的是 node2、node3 ......我以为是添加这些节点,但我意识到我不认为我实际上正在对这些节点及其值做任何事情,对吗?如何使用 setData() 和 setNext() 添加所有这些节点。那有意义吗?

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);

如果以上设置了这些值,我如何将它们全部添加?

然后我需要为每一项设置数据和下一步吗? (这似乎是多余的,因为我似乎在上面的构造函数中设置了每个节点 data 和 next 的值?)

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

我正在尝试添加所有上述节点,因此我可以通过添加新节点来测试我的 addLast() 方法。但是,当我在 main 中调用 addLast() 方法时,如下所示,唯一打印的是我添加的 addLast() 值(如果我调用 addFirst(),则首先打印)。

测试类

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();
    }
}

我没有添加我的其他两个课程,因为我认为这无关紧要,但如果您想看到它,请告诉我。我很新,这只是我的第二节课,它是在线的,而且课程结构很差,请多多关照,哈哈

单链表类

//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 类是你的基本getNext setNext, getData setData....

【问题讨论】:

  • 好的,所以我应该使用我在 main 开头设置的 SinglyLinkedList 对象来添加这些节点?
  • 我还是有点迷茫,我要贴出我的 SinglyLinkedList 类给你看看你能不能告诉我应该用什么方法来添加这些节点?我唯一能想到的是 addFirst() 方法,但是如何添加第一个节点之后的节点?这有意义吗?
  • 我明白了,这是有道理的,但我现在对 LinkedLists 最困惑的部分是如何添加多个节点。我看过的视频显示了像我这样的例子,我看到了如何设置值的结构以及下一个节点将是什么,但我实际上并没有添加这些值,我不知道如何添加。我想添加这些节点,这样我就可以更轻松地测试我编写的所有其他方法。
  • 我已将我的 cmets 移入答案以进行清理。

标签: java linked-list nodes implementation


【解决方案1】:

几点,主要是对cmets的总结:

您根本不应该使用main() 中的ListNode 对象——这应该是SinglyLinkedList 类的工作。 ListNode 甚至不需要对其余代码可见,它可以是 SinglyLinkedList 中的嵌套类。您应该只与SinglyLinkedList 交换数据对象(在这种情况下为字符串)。

如果您想测试 addLast() 方法,您可以从一个空列表开始并重复调用 list.addLast(),正如 Shane 在他的回答中提到的那样。这样,您将确保它在列表为空和非空时都能正常工作。

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

至于在一次调用中添加多个节点 - 此链接列表没有相应的方法。例如,您可以添加一个添加数组所有元素的方法,但您可以按顺序调用addLast(),效果相同。如果你想从一些基础数据开始测试其他方法,你可以在主类中创建一些辅助方法来填充列表。

附带说明:如果printList()java.io.PrintStream out 作为参数,您应该使用它而不是System.out。那是

out.println(...)

而不是

System.out.println(...)

另外,最好抛出 NoSuchElementException 而不是 NullPointerException 以指示请求的元素不存在。

如果你想要一种方便的方式来填充列表,你可以在你的主类中有这样的东西:

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

并像这样使用它:

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

【讨论】:

  • 哦,好吧,我想知道的基本上就是如何添加多个节点。本质上我需要一个简单的添加方法,或者我可以多次使用 addFirst 或 addLast 来填充 LinkedList?所以我正在观看的视频看起来就像你添加了我上面的节点,这种方法什么时候有用?或者将它们全部组合在一行中,例如 ....ListNode value = new ListNode("First", new ListNode("Second"....
  • 因为我的目标是从一些基础数据开始测试创建的新方法。
  • @sjud9227 您可以使用addFirst()addLast() 来填充列表,不同之处在于列表中值的顺序。然后可能会有add(int index) 添加到特定位置,但您不需要实现那个位置。您看到的视频可能是关于使用链接节点的一般情况,其中每个节点都可以单独使用。但是这里有一个列表,其中包含自己定义的方法,因此您只需要使用该类中的节点即可。
  • @sjud9227 请参阅我的编辑(在最后)以获取填充列表的方法示例。
  • 非常感谢辛南!你帮了我很多,我很感激你解释事情,我想学习不仅仅是得到答案。再次感谢您!
【解决方案2】:

你想做什么?如果您尝试填充链表,您需要做的就是不断调用 list.addLast,它将采用单个参数(您正在添加的新节点中的数据),并处理创建新节点和将其放在列表的最后。

我假设您不需要在主节点中创建任何节点,因为它们通常完全由链表类处理。

【讨论】:

  • 不,我想添加这些节点,以便我可以测试 addLast() 并确保它正常工作,但不仅仅是 addLast,我还有其他方法我正在尝试实现,我想使用包含这些节点的列表来测试其他方法
  • 仅供参考,不是我否决了你的答案 Shane。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多