我的 build() 方法的目的:要构建树,只需使用扫描仪继续阅读下一行。如果其中没有“/”,则将其推入堆栈。当您在一行中读取带有“/” ..()...的内容时,您将继续从堆栈中弹出,直到找到没有“/”的匹配标签 so 。弹出的所有内容都将作为兄弟姐妹连接,当您到达匹配标签的最终弹出窗口时,您将使其 firstChild 成为最后弹出的标签。
public void build() {
Stack<String> tags = new Stack<String>();
TagNode ptr = null;
String tmp = null;
if(tags.isEmpty() == true){ // base case
return;
}
while(sc.hasNextLine()){
String tag = sc.nextLine();
if(!tag.startsWith("</")){ //pushes everything that isn't a closing tag into the stack
tags.push(tag);
}else{ //a closing tag is found
tag.replaceAll("/", "");
while(!tags.peek().equals(tag)){ //now we start popping the stack in search of the opening tag
tmp = tags.peek();
tags.pop();
ptr = new TagNode(tmp, null, null);
ptr.sibling = ptr;
}// the opening tag is found
tmp = tags.peek();
tags.pop();
ptr = new TagNode(tmp, null, null);
ptr.firstChild = ptr;
}
}//we're at the last element in the stack
root = ptr.firstChild;
}