题目:将26个英文字母储存在链表中
#include <stdlib.h>
#include <stdio.h>
struct list
{
char Ach;
struct list* next;
};
void create( struct list* head , char* ch ) 而这个head是定义在局部函数的变量,当出局部函数的时候,head变量被销毁 ,而不会影响main函数中的head变量
{
char arr = *ch;
struct list* pf = NULL;
struct list* tail = NULL;
while( arr - 1 != 'z' )
{
struct list* pf = (struct list*)malloc(sizeof(struct list));
pf->Ach = arr++;
if( head == NULL )
{
head = pf;
}
else
{
tail->next = pf;
}
tail = pf;
}
tail->next = NULL;
}
void print( struct list* head )
{
struct list* pf = head;
while( pf != NULL )
{
printf("%c ",pf->Ach );
pf = pf->next ;
}
}
int main()
{
struct list* head = NULL; head是定义在main函数中的变量
char ch = 'a';
create(head,&ch);
print(head);
return 0;
}
此时不会打印出结果
原因:请看上面的代码解析
此时我们思考一下应该怎么做
当交换二个数时,应该传地址吧
#include <stdlib.h>
#include <stdio.h>
struct list
{
char Ach;
struct list* next;
};
void create( struct list** head , char* ch )
{
char arr = *ch;
struct list* pf = NULL;
struct list* tail = NULL;
while( arr - 1 != 'z' )
{
struct list* pf = (struct list*)malloc(sizeof(struct list));
pf->Ach = arr++;
if( *head == NULL )
{
*head = pf;
}
else
{
tail->next = pf;
}
tail = pf;
}
tail->next = NULL;
//return head;
}
void print( struct list* head )
{
struct list* pf = head;
while( pf != NULL )
{
printf("%c ",pf->Ach );
pf = pf->next ;
}
}
int main()
{
struct list* head = NULL;
char ch = 'a';
create(&head,&ch);
print(head);
return 0;
}