若有一个具有n(n>0)个整数的数列,采用以head为头指针的带头结点的单链表作存储结构,请编写求单链表长度的算法。
typedef strut node{
int data
struct node *next
}node;
int getListLength(node* nd) {
int cnt = 0; // (1) 用变量保存结点个数
while(nd) {
++cnt; // (2) 统计结点个数
nd = nd->next; // (3) 遍历到下一个结点
}
return cnt;
}
供参考:
typedef struct node{
int data;
struct node *next;
}Node;
int LinkList_Len(Node *Head)
{
Node* p = Head->next;
int len=0;
while(P)
{
len++;
p = p->next;
}
return len;
}