获取链表长度(迭代法和递归法)
迭代法
1、设定一个计数器,初始值为0
2、初始化current到头节点
3、如果current不为null进行以下循环
a) current = current -> next
b) count++;
4、返回计数器
c语言:
/* Counts no. of nodes in linked list */
int getCount(struct Node*head)
{
int count = 0; // Initialize count
struct Node* current = head; // Initialize current
while (current !=NULL)
{
count++;
current = current->next;
}
returncount;
}
java:
/* Returns count of nodes in linked list */
public intgetCount()
{
Node temp =head;
int count = 0;
while (temp != null)
{
count++;
temp =temp.next;
}
returncount;
}
c#