Measure size/length of singly linked list in Java?

亡梦爱人 提交于 2019-12-09 19:21:40

问题


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

Can someone help me implement this method in Java?


回答1:


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

You can write it like this.

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

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.

From LinkedList

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

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.




回答2:


The easiest way would be to have variable that tracks the size initialised at 0. Then each time you add a node it's just size++, or size-- when you remove a node. You size() method then just has to return this variable without traversing the list.




回答3:


You need to pass the list to your method and check currNode!= null :

public static int size(Node currNode){
    int count = 0;
    while (currNode!= null){
        count++;
        currNode=currNode.getNext();
    }
    return count;
}



回答4:


Well, the easiest way to calculate the length is by checking whether the currentNode!=null and keep the currentNode incrementing .

We can use while or a for loop to implement this.

Below is an example where for loop is used.

public int getLength(){
    ListNode temp = head;
    for(temp = head; temp!=null; temp=temp.getNextNode()){

        length++;
    }
    return length;
}


来源:https://stackoverflow.com/questions/12617021/measure-size-length-of-singly-linked-list-in-java

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