题目:
本题要求实现一个函数,求带头结点的单链表的表长。
函数接口定义:
int Length ( LinkList L ); |
其中LinkList结构定义如下:
typedef struct LNode { ElemType data; struct LNode *next; }LNode,*LinkList; |
L是带头结点的单链表的头指针,函数Length返回单链表的长度。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList Create();/* 细节在此不表 */
int Length ( LinkList L );
int main()
{
LinkList L = Create();
printf("%d\n", Length(L));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
2 1 4 5 3 -1 |
输出样例:
5 |
参考答案:
普通版:
int Length ( LinkList L ) {
if( L==NULL ) return 0;
int count=0;
while ( L->next != NULL && L->data != -1 ) {
++count;
L = L->next;
}
return count;
}
至尊版:
int lenth=0;
int Length ( LinkList L ) {
if ( L == NULL ) return 0;
if ( L->next != NULL && L->data != -1 ) {
lenth = lenth+1;
Length ( L->next );
}
return lenth;
}
// 利用递归和判断进行计数