BJP5练习16.7:deleteBack —帮助我了解解决方案 [英] BJP5 Exercise 16.7: deleteBack — Help me understand the solution
问题描述
我一直在练习ListNode
的练习,但感到非常沮丧,因为即使我认为我正确编写了代码(如下所示),也没有让我通过.
I have been working on this exercise to practice ListNode
s, and was very frustrated because even though I thought I wrote the code correctly (as shown below), it didn't let me pass.
public int deleteBack()
{
ListNode p = front;
if(p == null)
{
throw new NoSuchElementException();
}
if(p.next == null)
{
int data = p.data;
p = null;
return data;
}
while(p.next.next != null)
{
p = p.next;
}
int data = p.next.data;
p.next = null;
return data;
}
接下来,我尝试创建总共三个等于front
的新ListNode
.虽然,我不太清楚为什么这样做是必要的.
Next, I tried creating in total three new ListNode
s equal to front
. Although, I didn't quite see why this would be necessary.
public int deleteBack()
{
ListNode p = front;
if(p == null)
{
throw new NoSuchElementException();
}
ListNode q = front;
if(q.next == null)
{
int data = q.data;
q = null;
return data;
}
ListNode r = front;
while(r.next.next != null)
{
r = r.next;
}
int data = r.next.data;
r.next = null;
return data;
}
不幸的是,在我将q = null
更改为front = null
之前,这也给了我与以前相同的结果(仅通过了三个测试).更改之后,所有测试均通过.
Unfortunately, that also gave me the same result as before (passing only three tests), until I changed q = null
to front = null
. After this change, all tests were passed.
我想了解的是
- 为什么我的原始代码(对我来说似乎不错)不起作用.
- 为什么我必须创建多个等于
front
的ListNode
. - 为什么我必须设置
front = null
而不是q = null
.
- why my original code—which seems fine to me—doesn't work.
- why I had to create more than one
ListNode
equal tofront
. - why I had to set
front = null
instead ofq = null
.
我远远不满意.有人可以帮助我了解为什么需要进行这些更改吗?
I'm far from being satisfied. Could someone help me understand why these changes were necessary?
推荐答案
In your first case, front is already null (as its copy p is).
In your second case, you remove the last and only one value in the list, so front must become null as the list is now empty. Setting the local copy q to null doesn't take care of that.
In your 3rd case, there were more than 1 element in the list, so after removing the last element the list is not empty, and front must keep its not null value.
这篇关于BJP5练习16.7:deleteBack —帮助我了解解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!