我已经在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();
}如果length为>= 1,我如何弹出第一个元素?或者任何改进代码的建议。
发布于 2016-06-20 20:54:39
使用java.util.LinkedList。
您可以使用addFirst()、addLast()、size()、removeFirst()和removeLast()。
或者,检查此delimiter check example以了解另一种方法。
在您的代码中,您会遗漏“初始”或“最后一个元素”的大小写,这是很特殊的。您应该检查应该返回最后一个元素并清理列表的this.head == this.last;大小写。
发布于 2016-06-20 21:05:03
为什么要在循环中移动列表元素呢?不如这样吧:
if (this.head != null)
{
char val = this.head.getBracket();
this.head = this.head.getNextNode();
}这段代码将删除第一个元素,并将head设置为指向第二个元素。我猜JVM会删除旧的head。如果列表是循环的,那么还要将last设置为指向新的头部。
https://stackoverflow.com/questions/37922909
复制相似问题