繁体   English   中英

如何从相互连接的对象行的末端删除对象? (Java)

[英]How can I remove an object from the end of a line of objects connected to each other? (Java)

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

public class Dancer {

    private String name;
    private Dancer next;

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

我有这些设置方法。

要把它们串起来,我有一个CongaLine。

public class CongaLine {

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

    public CongaLine() {
        head = null;
    }

因此,使用while循环查找倒数第二个舞者,我如何从CongaLine中提取倒数第​​一个舞者?

我当前的方法有缺陷,看起来像这样:

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

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

  • 考虑一下最后一个舞者可以用来识别它的财产
  • 考虑一下如何确保与所有舞者相处,以便找到具有适当属性的舞者。
  • 考虑需要进行哪些其他更改(例如,倒数第二个舞者),以及如何确保始终进行这些更改。

这是一个链表 您必须在舞者之间循环,直到到达康茄舞线的尽头:

Dancer d = congaLine.getHead();
while(d.getNext() != null) {
  d = d.getNext();
}

在此d的结尾将是congaLine中的最后一位舞者。 您只需要为Dancer中的next舞者和CongaLine中的head舞者实现一个吸气剂即可。

暂无
暂无

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

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