本题要求实现一个函数,求链式表的表长。
函数接口定义:
int Length( List L );
其中List结构定义如下:
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode List;
L是给定单链表,函数Length要返回链式表的长度。
裁判测试程序样例:
#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;
}
/* 你的代码将被嵌在这里 */
输入样例:
1 3 4 5 2 -1
输出样例:
5
#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;
}
List Read()
{
int len = 0;
int num = 0;
PtrToLNode list = NULL;
PtrToLNode last = NULL;
scanf( "%d",&len );
if( len == 0 )
return NULL;
scanf( "%d",&num );
list = ( PtrToLNode )malloc( sizeof( PtrToLNode ) );
list->Data = num;
list->Next = NULL;
last = list;
len--;
while( len ){
scanf( "%d",&num );
PtrToLNode node = ( PtrToLNode )malloc( sizeof( PtrToLNode ) );
node->Data = num;
node->Next = NULL;
last->Next = node;
last = node;
len--;
}
return list;
}
int Length( List L ){
if(L==NULL) return 0;
else {
int len=1;
while(L->Next!=NULL){
len++;
L=L->Next;
}
return len;
}
}
题目链接: