我一直在研究链表,我试图在另一个节点之后删除一个节点。我有如何在当前节点之前删除但我现在需要后,我似乎无法弄明白。我让它工作一次,但它删除了当前不仅仅是当前的那个节点之后的每个节点。以下是在之前插入和删除之前的代码:
// 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();
}
}
}
感谢任何指导。
答案 0 :(得分:1)
用于删除单链表中包含给定项的项的代码包括:
代码可能类似于:
// 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();
}
}
}