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

查看:929
本文介绍了测量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和使用camelCase局部变量.

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中常用的类时,建议您看一下如何在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天全站免登陆