pta-数据结构与算法题目集(中文)-4-3 求链式表的表长
2015-10-15 00:00
621 查看
本题要求实现一个函数,求链式表的表长。
其中List结构定义如下:
L是给定单链表,函数Length要返回链式表的长度。
code:
函数接口定义:
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
code:
#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 num = 0;
scanf( "%d",&num );
if( -1 == num ){
return NULL;
}
List list = ( List )malloc( sizeof( struct LNode ) );
List last = list;
list->Data = num;
list->Next = NULL;
scanf( "%d",&num );
while( -1 != num ){
PtrToLNode node = ( List )malloc( sizeof( struct LNode ) );
node->Data = num;
node->Next = NULL;
last->Next = node;
last = node;
scanf( "%d",&num );
}
return list;
}
int Length( List L ){
PtrToLNode node = L;
int len = 0;
if( NULL == L ){
}
while( NULL != node ){
len++;
node = node->Next;
}
return len;
}
相关文章推荐
- 数据结构-链表
- 数据结构
- 【软/自考】算法写作思路
- 非递归实现二叉树的前、中、后序遍历
- 数据结构基础5_顺序栈的实现
- 面试小结三:关于算法数据结构的面试题整理(待续)
- 数据结构基础4_双链表的实现
- 数据结构实验之栈八:栈的基本操作
- 数据结构之队列
- *第七周*数据结构实践项目二【建设链式队列算法库】
- 【数据结构与算法】——插入排序
- 可视化的数据结构和算法
- 【队里项目4 - 队列数组】
- *第七周*数据结构实践项目一【建设环形队列算法库】
- 【队列项目3 - 负数把正数赶出队列--第7周】
- 详细介绍java中的数据结构
- 十大常用数据结构
- Objective-C的基础数据结构
- 数据结构简介
- hashmap的数据结构和算法