从链表中删除结束节点

时间:2015-09-23 14:08:23

标签: java 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--;
}

2 个答案:

答案 0 :(得分:0)

这种方法存在一些问题:

  • 你的方法是void而你想要返回最后一项的数据吗?

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

  • 您使用>2;

  • 还有一个角落,其中链表也可以为空。

可能更好的方法来解决这个问题:

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

答案 1 :(得分:0)

假设您不需要提取数据,只需删除最后一个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);
}

首先我们检查一个null或one-element列表;在那些情况下,没有什么可做的。

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

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

相关问题