6-1 Find the length of the linked list (10 points)
This question requires the realization of a function to find the length of the linked list.
Function interface definition:
int Length( List L );
The List structure is defined as follows:
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
}; typedef PtrToLNode List;
L is a given singly linked list, and the function Length returns the length of the linked list.
Sample referee test procedure:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode List;
List Read(); /* 细节在此不表 */
int Length( List L );
int main()
{
List L = Read();
printf("%d\n", Length(L));
return 0;
}
/* Your code will be embedded here */
Input sample:
1 3 4 5 2 -1
Sample output:
5
int Length( List L )
{
int cnt=0;
if(!L)
return 0;
while(L)
{
cnt++;
L = L->Next;
}
return cnt;
}