[英]POP method linked list
I've implemented a pop method in Java I would use it for delimiter matching, though it leaves one element in the list. 我在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();
}
How do I pop the first element if length is >= 1?, or any suggestion for improving my code. 如果长度> = 1,我如何弹出第一个元素?或者任何改进我的代码的建议。
Use java.util.LinkedList. 使用java.util.LinkedList。
With addFirst()
, addLast()
, size()
, removeFirst()
and removeLast()
you are covered. 使用
addFirst()
, addLast()
, size()
, removeFirst()
和removeLast()
您将获得覆盖。
Alternatively, check this delimiter check example for another way. 或者,以另一种方式检查此分隔符检查示例 。
In you code, you miss the "initial" or "last element" case, which is special. 在你的代码中,你会错过“初始”或“最后一个元素”的情况,这是特殊的。 You should check for the case of
this.head == this.last
; 你应该检查
this.head == this.last
的情况; case where you should return the last element and clean up the list. 应该返回最后一个元素并清理列表的情况。
Why moving through the list elements in the loop? 为什么要在循环中移动列表元素? How about instead of that:
怎么样而不是:
if (this.head != null)
{
char val = this.head.getBracket();
this.head = this.head.getNextNode();
}
This snippet will drop the first element and set head to point to the second element. 此片段将删除第一个元素并将头部设置为指向第二个元素。 I guess JVM will delete old
head
. 我猜JVM会删除旧
head
。 If the list is circular, then also set last
to point to the new head. 如果列表是循环的,那么也将
last
设置为指向新头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.