将递归修改为循环
请问下面代码如何修改成循环?我试着用2个stack来分别存储fields和values,还是没有实现。
哪位个忙。谢谢。
--------------------编程问答-------------------- 已经搞定了,使用一个stack实现 --------------------编程问答-------------------- --------------------编程问答-------------------- 望楼主分享成果,以供学习 --------------------编程问答--------------------
private void parseField(Parser parser, String target) {
List<Field> fields = processor.getPageRule(target).getFields();
for (Field field : fields) {
List<String> values = getValues(parser, field.getText());
if (StringUtils.isNotEmpty(field.getTarget())) {
for (int i = 0; i < values.size(); i++) {
Parser nextParser = new Parser(values.get(i));
parseField(nextParser, field.getTarget());
}
}
}
}
请优化,下列代码供参考:
--------------------编程问答-------------------- 除
private void parseField(JsoupParser parser, String target) throws Exception {
if (StringUtils.isEmpty(target)) {
return;
}
List<Field> fields = processor.getPageRule(target).getFields();
Stack<List<Field>> fieldStack = new Stack<List<Field>>();
Stack<String> targetStack = new Stack<String>();
Stack<List<String>> valueStack = new Stack<List<String>>();
Stack<JsoupParser> parserStack = new Stack<JsoupParser>();
fieldStack.push(fields);
parserStack.push(parser);
while (!fieldStack.isEmpty()) {
fields = fieldStack.pop();
for (Field field : fields) {
List<String> values = getValues(parser, field.getFieldValue());
System.out.println(field.getFieldName() + "\t" + values);
if (StringUtils.isNotEmpty(field.getTarget())) {
valueStack.push(values);
targetStack.push(target);
target = field.getTarget();
}
}
while (!valueStack.isEmpty()) {
List<String> values = valueStack.pop();
for (String url : values) {
parser = new JsoupParser(url, userAgent);
fields = processor.getPageRule(target).getFields();
parserStack.push(parser);
fieldStack.push(fields);
}
}
parser = parserStack.pop();
}
}
补充:Java , Java SE