从链表中删除结束节点

Removing the end node from a linked list

我缺少什么来允许我删除链表末尾的节点(boxcar)?

public void removeBoxcarFromEnd() {

    Boxcar prevcar = head;
    Boxcar nextcar = head;

    if (head.next == null) {
        int result = head.data;
        head = null;
        return result;
    }    
    else {
        while (nextcar.next() > 2)
        prevcar = nextcar;
        nextcar = nextcar.next();
    }
    prevcar.setNext(null);
    size--;
}

这种方法存在一些问题:

  • 你的方法是void而你想return最后一项的数据?

  • 您的 while 循环不使用括号 ({}) 也不使用缩进,因此只有 prevcar = nextcar 会无限次执行。

  • 你用>2;

  • 有一个cornercase,链表也可以为空

一个可能更好的处理方法:

public String removeBoxcarFromEnd() {
    String result;
    if(head == null) {  //empty list
        return null;      //or do something else? throw an exception?
    } else if (head.next() == null) {  //one element, remove it
        int result = head.data();
        head = null;
    }    
    else {  //more elements
        Boxcar prevcar = head, nextcar = head.next(), ffcar = nextcar.next();
        while (ffcar != null) {  //double next iteration
            prevcar = nextcar;
            nextcar = ffcar;
            ffcar = ffcar.next();
        }
        int result = nextcar.data(); //get result
        prevcar.setNext(null);       //remove it from the linked list
    }
    size--;
    return result;
}

假设不需要取数据,只去掉最后一个Boxcar:

public void removeBoxcarFromEnd() {
    Boxcar prevcar = head;
    Boxcar nextcar = head;

    if (head == null || head.next() == null) {
        return;
    }
    while (nextcar.next() != null) {
        prevcar = nextcar;
        nextcar = nextcar.next();
    }
    prevcar.setNext(null);
}

首先我们检查空列表或单元素列表;在那些情况下,没有什么可做的。

接下来我们遍历列表直到到达末尾(即 nextCar.next() returns null)。在每一步,我们都会保存我们传递的 Boxcar

当我们退出循环时,prevcar指向倒数第二辆车,我们可以安全地将它的next变量设置为null