1

我正在尝试创建一个公共 bool remove(E element) 方法,该方法删除包含该元素的第一个节点,如果没有找到这样的节点,则返回 false 否则为 true ...我该怎么做?我无法将已删除节点的前任链接到其后继节点以缩小由节点删除造成的差距......这是我到目前为止的代码......谢谢

public class SinglyLinkedList<E> {
private final SLNode<E> head;
private final SLNode<E> tail;
int length;

// creates an empty list
public SinglyLinkedList() {
    head = new SLNode<E>();
    tail = new SLNode<E>();
    head.setSuccessor(tail);
    length = 0;
}

// adds new node on beginning of the list
public void add(E element) {
    SLNode<E> node = new SLNode<E>(element, null);
    node.setSuccessor(head.getSuccessor());
    head.setSuccessor(node);
}

// adds new node on beginning of the list
public void add(SLNode<E> node) {
    node.setSuccessor(head.getSuccessor());
    head.setSuccessor(node);
}

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    SLNode<E> cursor = head.getSuccessor();
    while (cursor != tail) {
        sb.append(cursor.getElement()).append(" ");
        cursor = cursor.getSuccessor();
    }
    sb.append("\n");
    return sb.toString();
}
 }

节点类

public class SLNode<E> {
private E element;
private SLNode<E> successor;

public SLNode() {
    element = null;
    successor = null;
}

public SLNode(E theElement, SLNode<E> theSuccessor) {
    element = theElement;
    successor = theSuccessor;
}

public E getElement() {
    return element;
}

public void setElement(E newElement) {
    element = newElement;
}

public SLNode<E> getSuccessor() {
    return successor;
}

public void setSuccessor(SLNode<E> newSuccessor) {
    successor = newSuccessor;
}
  }
4

1 回答 1

0

诀窍是在迭代时,您需要保留对前一个元素和当前元素的引用。对前一个元素的引用可以让您缩小差距:

public boolean remove(E element) {
    SLNode<E> previous = head;
    SLNode<E> current = head.getSuccessor();

    while (current != tail) {
        if (current.getElement().equals(element)) {
            previous.setSuccessor(current.getSuccessor());

            return true;
        }

        previous = current;
        current = current.getSuccessor();
    }

    return false;
}
于 2012-09-18T23:57:10.173 回答