我目前正在编写单链接列表的代码。如何将对象作为参数传入单个链表后删除元素?
这是删除列表最后一个元素的方法
public Object removeLast() throws EmptyListException {
if (head == null) throw new EmptyListException();
Object o;
// If there is only one element, we need to modify the head of the list
if (head.next == null) {
o = head.content;
head.content = null;
head = null;
return o;
}
Node crt = head;
while (crt.next.next != null)
crt = crt.next;
o = crt.next.content;
// Remove all references that are not needed
crt.next.content = null;
crt.next = null;
return o;
}
答案 0 :(得分:1)
这是伪代码算法。如果你不介意的话,你可以将它翻译成Java;)
removeAfter(elem):
if head == null -> error // empty list
current = head
while current != null && current != elem:
current = current.next
;
if current == null -> error // elem not found
if current.next == null -> error // no more item after elem
content = curent.next.content
current.next = current.next.next
return content
;