[使用递归在堆栈中搜索的方法

问题描述 投票:0回答:1

我需要使用递归搜索堆栈中的元素我不能使用其他数据结构我无法更改堆栈这是我所做的,这是错误的

public static<E> boolean se(LinkedStack<E>s,E a) {
    boolean answer=false;
    E tmp=s.pop();
    if(tmp==a)
        answer= true;
    else {
        se(s, a);
        s.push(tmp);
    }
    return answer;
}
java recursion search stack
1个回答
0
投票
您需要使用(即设置答案)递归调用se的结果。

public static<E> boolean se(LinkedStack<E>s,E a) { boolean answer=false; E tmp=s.pop(); if(tmp==a) answer= true; else { answer = se(s, a); s.push(tmp); } return answer; }

© www.soinside.com 2019 - 2024. All rights reserved.