一个简单的关于的链表疑问。解决方案
一个简单的关于的链表疑问。。。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct list
{
char data;
struct list *next;
};
int main()
{
char a[10]={ 'a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ', 'h ', 'j ', 'k '};
char b;
struct list *head,*p1,*p2;
//scanf( "%c\n ",&b);
p1=head=(struct list*)malloc(sizeof(struct list));
if(head==NULL)
{
printf( "error ");
}
else
{
for (int i=0;i <10;i++)
{
p2=(struct list*)malloc(sizeof(struct list));
p2-> data=a[i];
p1-> next=p2;
p1=p2;
}
p1-> next=NULL;
}
while(head!=NULL)
{
printf( "%c ",head-> data);
head=head-> next;
}
getch();
}
为什么我的结果前面会有个空格,应该是null值吧。
在链表的时候,我先开辟内存 p1=head=(struct list*)malloc(sizeof(struct list));,然后再给p1赋值,为什么之前开辟内存时的null值,到了后面还会在呢?????这个怎么解决????
------解决方案--------------------
你的那个head是什么意思?那是一个头结点,你的程序里面头结点的data域是没有任何的意义的。你打印的时候打印了这个数值,这个数值是一个随即的数值,在你的程序里面,它作为一个字符可能是不可显示的,所以就会出现空格。
解决办法,在你打印的语句中不要输出头结点的data就可以了。
------解决方案--------------------
while(head!=NULL)
{
printf( "%c ",head-> data);
head=head-> next;
}
------------
前面加一句:
head=head-> next;
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct list
{
char data;
struct list *next;
};
int main()
{
char a[10]={ 'a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ', 'h ', 'j ', 'k '};
char b;
struct list *head,*p1,*p2;
//scanf( "%c\n ",&b);
p1=head=(struct list*)malloc(sizeof(struct list));
if(head==NULL)
{
printf( "error ");
}
else
{
for (int i=0;i <10;i++)
{
p2=(struct list*)malloc(sizeof(struct list));
p2-> data=a[i];
p1-> next=p2;
p1=p2;
}
p1-> next=NULL;
}
while(head!=NULL)
{
printf( "%c ",head-> data);
head=head-> next;
}
getch();
}
为什么我的结果前面会有个空格,应该是null值吧。
在链表的时候,我先开辟内存 p1=head=(struct list*)malloc(sizeof(struct list));,然后再给p1赋值,为什么之前开辟内存时的null值,到了后面还会在呢?????这个怎么解决????
------解决方案--------------------
你的那个head是什么意思?那是一个头结点,你的程序里面头结点的data域是没有任何的意义的。你打印的时候打印了这个数值,这个数值是一个随即的数值,在你的程序里面,它作为一个字符可能是不可显示的,所以就会出现空格。
解决办法,在你打印的语句中不要输出头结点的data就可以了。
------解决方案--------------------
while(head!=NULL)
{
printf( "%c ",head-> data);
head=head-> next;
}
------------
前面加一句:
head=head-> next;