我在 Java 中实现了一种 pop 方法,我将使用它来进行分隔符匹配,尽管它会在列表中留下一个元素。
public int length(){
Node current = this.head;
int length = 0;
while(current != null){
current = current.getNextNode();
length += 1;
}
return length;
}
public char pop(){
Node current = this.head;
Node lastN = this.last;
for(int i = 0; i < length() - 2; i++){
current = current.getNextNode();
}
current.setNextNode(null);
this.last = current;
return lastN.getBracket();
}
如果长度 >= 1,如何弹出第一个元素?或者任何改进代码的建议。
最佳答案
使用java.util.LinkedList。
使用 addFirst()
、addLast()
、size()
、removeFirst()
和 removeLast()
即可满足您的需求。
或者,检查此 delimiter check example另一种方式。
在您的代码中,您错过了“初始”或“最后一个元素”的情况,这是特殊的。您应该检查 this.head == this.last
的情况;在这种情况下,您应该返回最后一个元素并清理列表。
关于java - POP方法链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37922909/