编写C函数来计算给定单链表中的节点数。
例如,对于链接列表1-> 3-> 1-> 2-> 1,该函数应返回5。
迭代解决方案
1)将计数初始化为0
2)初始化节点指针,current = head。
3)当current不为NULL时执行以下操作
a)current=current->next
b)count ++;
4)返回计数
以下是算法是C/C++实现,以查找节点数
// Iterative C program to find length or count of nodes in a linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts no. of nodes in linked list */
int getCount(struct Node* head)
{
int count = 0; // Initialize count