简体   繁体   English

从链表中删除端节点

[英]Removing the end node from a linked list

What am I missing to allow me to remove a node(boxcar) to the end of my linked list? 我缺少什么让我可以删除节点(盒子车)到链表的末尾?

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--;
}

There are a few problems with this approach: 这种方法存在一些问题:

  • you're method is a void whereas you want to return the data of the last item? 您的方法是void而您想返回最后一项的数据?

  • your while loop doesn't use brackets ( {} ) nor indentation, therefore only prevcar = nextcar will be executed an infinite amount of times. 您的while循环不使用方括号( {} )或缩进,因此仅prevcar = nextcar将被执行无限次。

  • you use >2 ; 您使用>2 ;

  • there is a cornercase where the linked list can be empty as well. 在一个极端的情况下,链表也可以为空。

A probably better way to handle this: 解决这个问题的更好方法:

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;
}

Assuming you don't need to fetch data, only remove the last Boxcar : 假设您不需要获取数据,只需删除最后一个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);
}

First we check for a null or one-element list; 首先,我们检查是否为空或单元素列表; in those cases, there's nothing to do. 在这些情况下,无需执行任何操作。

Next we walk the list until we get to the end (ie nextCar.next() returns null). 接下来,我们遍历该列表,直到到达结尾为止(即nextCar.next()返回null)。 At each step, we save the Boxcar that we're passsing. 在每一步,我们都保存正在传递的Boxcar

When we exit the loop, prevcar points to the second-to-last car, and we can safely set its next variable to null . 退出循环时, prevcar指向倒数第二辆汽车,我们可以安全地将其next变量设置为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM