In this method I keep getting a return value of One even after I add more nodes

夙愿已清 提交于 2019-12-25 05:38:30

问题


Got a quick question, this is part of a linked list. It determines what the size of the list is, it doesnt work very well at the moment because it keeps returning a 1 even after I add more nodes.

public int size(){
ListNode currentNode = null;
ListNode previousNode = null;
int numberOfNodes = 0;

if (head == null) return 0;

previousNode = head;
currentNode = head.next;

numberOfNodes++;

while (currentNode != null){
    previousNode = currentNode;
    currentNode = currentNode.next;
    numberOfNodes++;
}
return numberOfNodes;

}

回答1:


If the addNode function is as the one in here then you have an error:

Last line should be

    previousNode.next = newNode;

instead of

    newNode = previousNode.next;



回答2:


Too much clutter in this code, try the following:

public int size() {
  int numberOfNodes = 0;
  ListNode currentNode = head;
  while (currentNode != null){
    numberOfNodes++;
    currentNode = currentNode.next;
  }
  return numberOfNodes;
}


来源:https://stackoverflow.com/questions/6558658/in-this-method-i-keep-getting-a-return-value-of-one-even-after-i-add-more-nodes

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