The following source code is found from the post "数据结构算法实现及解析》—配合严蔚敏_吴伟民编....jing314提供数据[长] [ 2 3 4 ]"
{ /* 初始条件:线性表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.
{ /* 初始条件:线性表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编辑过]