我无法弄清楚为什么我在下面定义的 len() 函数中少计数 1。len() 函数应该计算我的链表中元素的数量。
struct node {
int data;
struct node* link;
};
typedef struct node node;
node *root=NULL;
void append(void);
int len(void);
int main(void) {
printf("\nCurrent length of list:\t%d\n",len());
append();
printf("\nCurrent length of list:\t%d\n",len());
append();
printf("\nCurrent length of list:\t%d\n",len());
append();
printf("\nCurrent length of list:\t%d\n",len());
return 0;
}
void append(void) {
node *tmp;
tmp=(node *)malloc(sizeof(node));
printf("\nEnter data value\t\n");
scanf("%d", &tmp->data);
tmp->link=NULL;
if(root==NULL){
root=tmp;
}
else{
node *ptr=root;
while(ptr->link!=NULL){
ptr=ptr->link;
}
ptr->link=tmp;
}
}
int len(void) {
int cnt=0;
if(root==NULL)
return 0;
node *tmp=root;
while(tmp->link!=NULL){
++cnt;
tmp=tmp->link;
}
return cnt;
}
列表的当前长度:0 // 调用 len(),预期输出:正确
输入数据值 20 // 调用 append()
列表的当前长度:0 // 调用 len(),预期输出:1
输入数据值 191 // 调用 append()
列表的当前长度:1 // 调用 len(),预期输出:2
输入数据值 22 // 调用 append()
列表的当前长度:2 // 调用 len(),预期输出:3
你没有计算最后一个元素。尝试跟踪您的代码。
如果您的链表如下所示
elem1 -> elem2 -> elem3 -> NULL
您计算元素 1 和 2 但不计算 3,因为 3 的link
字段为 NULL。
将您的代码更改为以下内容,它将起作用
int len(void){
int cnt=0;
node *tmp=root;
while(tmp!=NULL){
++cnt;
tmp=tmp->link;
}
return cnt;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句