在 Java 中测量单向链表的大小/长度? [英] Measure size/length of singly linked list in Java?

查看:28
本文介绍了在 Java 中测量单向链表的大小/长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助为 Java 中的单向链表制作 int size(); 方法.

I need help making the int size(); method for a singly linked list in Java.

这是我目前所拥有的,但它没有返回列表的正确大小.

This is what I have so far, but it does not return the correct size of the list.

public int size()
{
    int size = 0;
    Node CurrNode = head;
    while(CurrNode.next != null)
    {
        CurrNode = CurrNode.next;
        size++;     
    }
    return size;
}

有人可以帮我用 Java 实现这个方法吗?

Can someone help me implement this method in Java?

推荐答案

你能做出的最大改进是使用 Java Coding Convension 和使用驼峰式局部变量.

The biggest improvement you can make is to use Java Coding Convension and use camelCase local variables.

你可以这样写.

public int size() {
   int size = 0;
   for(Node n = head; n.next != null; n = n.next)
       size++;     
   return size;
}

因为您正在用 Java 重写一个常用的类,所以如果您想要更好的做事方式,我建议您看看它是如何完成的.

as you are re-writing a commonly used class in Java, I suggest you have a look at how it is done there if you want a better way of doing things.

来自 LinkedList

/**
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
    return size;
}

正如你所看到的,当一个元素被添加时,尺寸会增加,当一个元素被移除时,它的 id 会减少,这样你就不必遍历列表来获取尺寸了.

As you can see, when an element is added size is incremented and when an element is removed it id decremented saving you having to traverse the list to get the size.

这篇关于在 Java 中测量单向链表的大小/长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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