BJP5 Exercise 16.7: deleteBack — Help me understand the solution

拥有回忆 提交于 2020-01-16 14:07:45

问题


I have been working on this exercise to practice ListNodes, 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 ListNodes 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 to front.
  • why I had to set front = null instead of q = 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!