BJP5练习16.7:deleteBack —帮助我了解解决方案 [英] BJP5 Exercise 16.7: deleteBack — Help me understand the solution

查看:80
本文介绍了BJP5练习16.7:deleteBack —帮助我了解解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在练习ListNode的练习,但感到非常沮丧,因为即使我认为我正确编写了代码(如下所示),也没有让我通过.

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;
}

接下来,我尝试创建总共三个等于front的新ListNode.虽然,我不太清楚为什么这样做是必要的.

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;
}

不幸的是,在我将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.

我想了解的是

  • 为什么我的原始代码(对我来说似乎不错)不起作用.
  • 为什么我必须创建多个等于frontListNode.
  • 为什么我必须设置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 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?

推荐答案

在您的第一种情况下,front已经为空(因为其副本p为).
在第二种情况下,将删除列表中的最后一个值,并且仅删除一个值,因此front必须变为null,因为列表现在为空.将本地副本q设置为null不会解决此问题.
在第3种情况下,列表中有多个元素,因此,删除最后一个元素后,列表不为空,并且front必须保持其非null值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆