0

次のようなクラスがある場合:

class Node
{
    string id;
    const Node next;
}

たとえば、リンクリストidの最後のものを見つけるにはどうすればよいですか?Node

string lastID(const Node node)
{
    ???
}
4

2 に答える 2

3

I assume that your problem is that you need to loop but can't reset your variable, because it's const? If you want to have an object which refers to a const object but is re-assignable itself (i.e. it's tail-const), then use std.typecons.Rebindable. In this case, that gives you:

string lastID(const Node node)
{
    import std.typecons;
    Rebindable!(const Node) curr = node;

    while(curr.next)
        curr = curr.next;

    return curr.id;
}

I must say that I find it a bit odd though that you don't just ask about how to have a reference to a const object where the reference isn't const itself, since that's all I can see that you're really asking here, given how straightforward the loop itself is. As it stands, your question is a bit too much along the lines of asking someone to write your code for you rather than asking a question.

于 2012-09-20T05:51:29.923 に答える
2

凝って再帰を使うこともできます:

string lastID(const Node node)
{
    if(node.next)
        return lastID(node.next);
    return node.id;
}

リストが非常に長い場合、スタック オーバーフローが発生する可能性があることに注意してください (私の知る限り、D は末尾呼び出し再帰の最適化をサポートしていません)。

于 2012-09-20T07:10:10.733 に答える