单向链表 程序检错

来源:百度知道 编辑:UC知道 时间:2024/06/09 05:06:07
#include "stdlib.h"
#include "stdio.h"
typedef struct word{
char a;
struct word *next;
};
void main()
{
int i,size;
struct word *head,*p,*q;
size=sizeof(struct word);
head=(void*)malloc(size);
p=head;
for(i=1;i<26;i++){
p->a='a'+i-1;
q=(void*)malloc(size);
p->next=q;
p=p->next;
}
p->a='z';
p->next=NULL;
for(p=head;p->next!=NULL;p=p->next)
printf("%c\t",p->a);
}
为什么该程序结果不能输出z
#include "stdlib.h"
#include "stdio.h"
typedef struct word{
char a;
struct word *next;
}*word;
void main()
{
int i,size;
struct word *head,*p,*q;
size=sizeof(struct word);
head=(word)malloc(size);
p=head;
for(i=1;i<26;i++){
p->a='a'+i-1;
size=sizeof(struct word);
q=(word)mall

for(p=head;p->next!=NULL;p=p->next)
printf("%c\t",p->a);
当到达p->a=='z'的时候正好是p->next==NULL,所以它不会执行printf("%c\t",p->a);
再写一句就可以了
for(p=head;p->next!=NULL;p=p->next)
printf("%c\t",p->a);
printf("%c\t",p->a);

#####################################
for(p=head;p->next!=NULL;p=p->next)
判断终止条件就不同,上一个是在判断下一个指针是否存在(为NULL),当到达z之后,下一个位置确实为空,则不在执行,跳出循环,而下面的是在判断当前的指针是否为NULL,当到达Z的位置时,当前的指针不是为空,就输出了Z
for(p=head;p!=NULL;p=p->next)