下面的代码创建了一个链表,[java, python, java2]
NodeStr first = new NodeStr("java");
NodeStr second = new NodeStr("python");
NodeStr third = new NodeStr("java2");
first.setNext(second);
second.setNext(third);要删除尾节点,我们需要找到尾节点的上一个节点,使尾节点游离接口,GC会回收它。
NodeStr p = first;
while (p.getNext() != null && p.getNext().getNext() != null)
{
p = p.getNext();
}现在p指向了上一个节点,如果链表只有一个元素,我们将first设为Null接口。如果多余一个,我们将p.next = null,是尾节点游离:
if (p.getNext() == null)
{
p = null;
first = null;
}
else if (p.getNext().getNext() == null)
{
p.setNext(null);
}完整代码:
public static void main(String[] args)
{
NodeStr first = new NodeStr("java");
NodeStr second = new NodeStr("python");
NodeStr third = new NodeStr("java2");
first.setNext(second);
second.setNext(third);
NodeStr p = first;
while (p.getNext() != null && p.getNext().getNext() != null)
{
p = p.getNext();
}
if (p.getNext() == null)
{
p = null;
first = null;
}
else if (p.getNext().getNext() == null)
{
p.setNext(null);
}
NodeStr p2 = first;
while (p2 != null)
{
System.out.println(p2.getItem());
p2 = p2.getNext();
}
}