[英]removing element from LinkedList
I'm trying to remove the last node from a linkedList and return it. 我正在尝试从链表中删除最后一个节点并返回它。 This is part of a Linkedlist class.
这是Linkedlist类的一部分。 The following method that I wrote doesn't delete the last node.
我编写的以下方法不会删除最后一个节点。 Does anybody know why?
有人知道为什么吗?
public int delete(){
if(front==null){
throw new NoSuchElementException();
}else{
ListNode current = front;
while(current.next!=null){
current = current.next;
}
int delete = current.data;
current = null;
return delete;
}
}
Setting current
to null only changes the reference to null. 将
current
设置为null只会将引用更改为null。 It in no way affects the linked list data structure. 它决不会影响链表数据结构。 You need to find the second to last node and set its next pointer to null:
您需要找到倒数第二个节点,并将其下一个指针设置为null:
int data = secondToLastNode.next.data;
secondToLastNode.next = null;
return data;
Of course, you'll need to handle the situation where there is only one node in the list which the above code doesn't account for. 当然,您需要处理以下情况:列表中只有一个节点,上面的代码没有考虑。
You are only setting your local reference current
to null
; 您仅将本地参考
current
设置为null
; you're not changing your list. 您没有更改列表。
Assuming this is a singly linked list, you will need to set the second-to-last ListNode
's next
to null
(or set front
to null
if it's the only item). 假设这是一个单向链表,你将需要设置第二个到最后
ListNode
的next
,以null
(或一组front
向null
,如果它是唯一的项目)。
There are three situations you need to cover: 您需要解决三种情况:
front
will have a value but front.next
will be null
. front
将具有一个值,但是front.next
将为null
。 You should set front
to null
in this case. front
设置为null
。 next
of the last but one entry to null
. next
一个条目设置为null
。 You have not managed to do this yet. Remember the 'current' before the one that has the null pointer, and set the 'next' pointer of that node to null. 记住具有空指针的指针之前的“当前”指针,并将该节点的“下一个”指针设置为空。 That way, you delete the reference to the latest node, instead of just updating a local variable.
这样,您将删除对最新节点的引用,而不仅仅是更新局部变量。
Try this one 试试这个
public int delete(){
if(front==null){
throw new NoSuchElementException();
} else if(front.next===null){
return front.data;
}else{
ListNode current = front;
while(current.next.next!=null){
current = current.next;
}
int deleted_node = current.next.data;
current.next = null;
return deleted_node;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.