递归写入find方法,LinkedList

时间:2012-11-27 01:42:20

标签: java recursion linked-list

我需要递归地编写find方法,当我试图找到x并找到它时 我需要将x移动到链表的头部

例如,如果列表是 头 - > 15 - > 20 - > 5 - > 10

我运行find(5),然后列表将是 头 - > 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;
        }
    } 
}

3 个答案:

答案 0 :(得分: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方法,则可以删除相应的节点,并将节点添加到列表的前面第二个find作为包含x的新节点(假设find(x, head)返回true)。

答案 1 :(得分:0)

私有布尔查找(int x) {  Node retval = recursiveFind(x,head,parent)  如果retVal!= null RetVal.next =头  回归真实 }

私有节点recursiveFind(Int x,节点头,节点父节点) { 如果head == null&& parent == null 返回null;

如果head.value == x Parent.next = head.next: 回头

否则返回recursiveFind(x,head.next,head)

我在使用smatphone但是有类似的东西

一些

答案 2 :(得分: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()方法期间保留对前一节点的引用,并将其返回到包含搜索目标的下一个节点之后,并从列表中删除。

相关问题