java - 如何从相互连接的一排对象的末尾删除一个对象? ( java )

标签 java object loops while-loop

换句话说,我有一行 Dancer 对象。

public class Dancer {

    private String name;
    private Dancer next;

    public Dancer(String nameInput, Dancer followingDancer){
        name = nameInput;
        next = followingDancer;
    }

我有这些的 setter 和 getter。

为了将这些串起来,我有一个 CongaLine。

public class CongaLine {

    private Dancer head; // first dancer in the conga line.

    public CongaLine() {
        head = null;
    }

那么,使用 while 循环查找倒数第二个 Dancer,我如何找到从 CongaLine 中提取的最后一个 Dancer?

我目前的方法是有缺陷的,如下所示:

public String removeFromEnd() {
    String removed = null;
    // For multiple dancers, find the penultimate and remove its "next"
    while (head.getNext() != null) {
        if (head.getNext().getNext() == null){
        removed = head.getNext().getName();
        head.setNext(null);
        }
    }
    // In the case of only one dancer, remove that dancer.
    if (head != null && head.getNext() == null) {
        removed = head.getName();
        head = null;
    }
    return removed;
}

最佳答案

嗯,我可以给你确切的代码(只有几行),但我认为既然你这样做是为了学习,最好给出一些提示:

  • 想想最后的舞者有什么属性可以用来识别它。
  • 想一想如何确保您审视所有舞者,以便找到具有合适属性的舞者。
  • 考虑需要发生哪些其他变化(例如倒数第二个舞者),以及如何确保始终发生这些变化。

关于java - 如何从相互连接的一排对象的末尾删除一个对象? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9406084/

相关文章:

linux - 打破循环的 Bash 函数

loops - 关于kattis问题: texture analysis的错误答案

java - 使用 java 拖放并识别位置

java - 新手数组问题

java - Hadoop map reduce 总是写入相同的值

java - 更改 HashSet 中的值

c++ - 如何从一个类调用另一个类的函数而不需要继承

javascript - jQuery 对象字面量函数声明错误

arrays - Swift - 按另一个数组的属性对对象数组进行排序

delphi - 如何使用 Delphi 6 迭代初始化枚举类型并避免 "out of bounds"错误?