问题
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;
}
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;
}
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.
What I'm trying to understand is
- 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?
回答1:
https://practiceit.cs.washington.edu/problem/view/bjp5/chapter16/e7-deleteBack
asks that private ListNode front; // null for an empty list
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.
来源:https://stackoverflow.com/questions/58847642/bjp5-exercise-16-7-deleteback-help-me-understand-the-solution