0

find メソッドを再帰的に記述する必要があり、x を見つけようとして見つけたときに、x をリンクされたリストの先頭に移動する必要があります。

たとえば、リストが head --> 15 --> 20 --> 5 --> 10 の場合

find(5) を実行すると、リストは head --> 5 --> 15 --> 20 --> 10 になります。

private boolean find (int x)
{
    Node pointer = head;
    int i = 0;
    while(pointer != null)
    {
        if( pointer.data != x)
        {
            pointer = pointer.next;
            find(x);      
        }
        else
        {
            return true;
        }
    } 
}
4

3 に答える 3

1

次のような再帰ヘルパー メソッドを作成する必要があると思います。

private boolean find(int x, Node node) {
    if (node == null)
        return false;
    return node.data == x || find(x, node.next);
}

その場合、標準findは単純に

private boolean find(int x) {
    return find(x, head);  // start search from head
}

追加/削除コンポーネントは、このアプローチを念頭に置いて実装するのは難しくありません。最初のfindメソッドで適切なノードが見つかった場合は削除し、2 番目のメソッドで(findを含む新しいノードとしてそのノードをリストの先頭に追加します)。 true を返すとx仮定します)。find(x, head)

于 2012-11-27T01:49:03.950 に答える
0

Java とリンクされたリストをいじらなければならなかった (そしてテストせずに頭のてっぺんから書いた) ので、これはコピー/貼り付けではうまくいかないかもしれませんが、次のようなことを試してください:

Node linkedListHead = ...;

public void find(int target){
    Node foundNode = findRec(target, linkedListHead, null);

    if(foundNode != null){
        // assumes Node takes in the Data first, then a Node
        linkedListHead = new Node(target, linkedListHead);
        foundNode.next = foundNode.next.next;
    }
}

private void findRec(int target, Node currentNode, Node previousNode){

    if(currentNode == null){
        return null;

    } else if(currentNode.data == target){
        return previousNode;

    } else {
        return find(target, currentNode.next, currentNode);
    }
}

ポイントは、findRec() メソッド中に前のノードへの参照を保持し、それを次のノード (検索対象を含む) に返し、リストから削除することです。

于 2012-11-27T01:57:49.913 に答える
0

Private boolean find(int x) { Node retval = recursiveFind(x, head, parent) If retVal != null RetVal.next = head Return true }

Private Node recursiveFind(Int x, node head, node parent) { If head == null && parent == null Return null;

head.value == x Parent.next = head.next の場合: 先頭を返す

それ以外の場合は recursiveFind(x, head.next, head) を返します

スマホだけどそんな感じ

いくつか

于 2012-11-27T01:54:55.400 に答える