在方法java之后删除Linked-List

时间:2016-05-11 09:55:58

标签: java algorithm linked-list

我一直在研究链表,我试图在另一个节点之后删除一个节点。我有如何在当前节点之前删除但我现在需要后,我似乎无法弄明白。我让它工作一次,但它删除了当前不仅仅是当前的那个节点之后的每个节点。以下是在之前插入和删除之前的代码:

// Remove the node containing item nVal
public void removeBefore(E curVal, E nVal) {
    // You implement this method for Assignment 2
    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) {

            newNode.setNext(curr);
            prev.setNext(newNode);
            break;
        } else {
            // advanced curr and prev
            prev = null;
            curr = curr.getNext();
        }
    }
}


// Insert new node nVal to the list after current node curVal 
public void insertNodeAfter(E nVal, E curVal) {
    // You implement this method for Week 11 tutorial
    Node<E> newNode = new Node<E>(nVal);

    Node<E> curr = head;

    // scan until locate node or come to end of list
    while (curr != null) {
        // have a match 
        // Replaced == with .equals
        if (curr.getNodeValue().equals(curVal)) {
            // insert node
            newNode.setNext(curr.getNext());
            curr.setNext(newNode);
            break;
        } else {
            curr = curr.getNext();
        }
    }
}

感谢任何指导。

1 个答案:

答案 0 :(得分:1)

用于删除单链表中包含给定项的项的代码包括:

  • 从头部搜索列表中的值,跟踪上一个节点
  • 如果节点是第一个(previous为null),则在下一个
  • 开始列表
  • 否则,将前一个点直接指向next(也适用于最后一个节点)

代码可能类似于:

// Remove the node containing item nVal
public void remove(E curVal) {
    Node<E> curr = head;
    Node<E> prev = null;


    // scan until locate node or come to end of list
    while (curr != null) {
        // have a match 
        if (curr.getNodeValue().equals(curVal)) {

            if (prev == null) {  // curr is first node: just start to next
                head = curr.getNext();
            }
            else {   // make prev point to next
                prev.setNext(curr.getNext());
            }
            break;
        } else {
            // advanced curr and prev
            prev = curr;
            curr = curr.getNext();
        }
    }
}