小编Pat*_*Pat的帖子

LinkedList 在节点后插入

我一直在尝试使用 Java 在当前节点之后将节点插入到链表中。我已经能够在当前节点之前插入,但我无法让它工作:

这是 的代码insertNodeBefore。我只想知道是否有办法调整它以便能够在当前节点之后插入?

// Insert new node nVal to the list before current node curVal 
public void insertNodeBefore(E nVal, E curVal) {
    Node<E> newNode = new Node<E>(nVal);

    Node<E> curr = head;
    Node<E> prev = null;

    if (head.getNodeValue() == curVal) {
        newNode.setNext(head);
        head = newNode;
        return;
    }

    // scan until locate node or come to end of list
    while (curr != null) {
        // have a match 
        if (curr.getNodeValue() == curVal) {
            // insert node
            newNode.setNext(curr);
            prev.setNext(newNode); …
Run Code Online (Sandbox Code Playgroud)

java algorithm linked-list

4
推荐指数
1
解决办法
4491
查看次数

标签 统计

algorithm ×1

java ×1

linked-list ×1