| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 759 人关注过本帖
标题:[经验] Is this piece of source code for ListLength(LinkList L) optimi ...
只看楼主 加入收藏
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
 问题点数:0 回复次数:1 
[经验] Is this piece of source code for ListLength(LinkList L) optimized?

The following source code is found from the post "数据结构算法实现及解析》—配合严蔚敏_吴伟民编....jing314提供数据[长] [ 2 3 4 ]"

int ListLength(PNode L)
{ /* 初始条件:线性表L已存在。操作结果:返回L中数据元素个数 */
int i=0;
PNode p=L;
while(p) /* p指向结点(没到表尾) */
{
p=p->next; /* p指向下一个结点 */
i++;
}
return i;
}


Is this piece of source code optimized? Think a second time if your answer is yes.



No, it is not, because it uses 4 bytes of memory more than necessary.

You laugh at me and say: "4 bytes of memory, it is not a big deal." Yes, you are right in most cases, it does not hurt for a PC or Mac. However, if you are developping software that applies to a cell phone or a PDA, you may want to save that 4 bytes.

When we pass the argument L by value, we sign a contract with the function ListLength() that when it returns any modification made to L is discarded. Thus there is no risk that you will modify the link list.

typedef int ELemType;

typedef struct Node
{
ElemType data;
struct Node* next;
} Node, *PNode;


A sample modification is here. Notice that as a matter of fact, L is NULL or 0, when the while loop ends.

int ListLength(PNode L)
{ /* 初始条件:线性表L已存在。操作结果:返回L中数据元素个数 */
int i=0;
// PNode p=L;// no need of this pointer p
while(L) /* p指向结点(没到表尾) */
{
L=L->next; /* L指向下一个结点 */
++i;
}
return i;
}

[此贴子已经被作者于2007-6-10 9:19:05编辑过]

搜索更多相关主题的帖子: piece source LinkList ListLength optimized 
2007-06-10 09:14
nuciewth
Rank: 14Rank: 14Rank: 14Rank: 14
来 自:我爱龙龙
等 级:贵宾
威 望:104
帖 子:9786
专家分:208
注 册:2006-5-23
收藏
得分:0 
英文.

支持一下.

倚天照海花无数,流水高山心自知。
2007-06-10 12:12
快速回复:[经验] Is this piece of source code for ListLength(LinkList L) o ...
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.025484 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved