迷惑链表1(高手指教指教吧)
#include<malloc.h>
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}NODE;
NODE *create()/*才用后插入方式建立单链表,并返回一个指向链表表头的指针,建立空表*/
{
NODE *head,*q,*p;
char ch;
int a;
head=(NODE*)malloc(sizeof(NODE));
q=head;
ch='*';
printf("/nInput the list:");
while(ch!='?') /*'ch'为是否建立新结点的标志,若'ch'为'?'则输入结束*/
{
scanf("%d",&a);
p=(NODE*)malloc(sizeof(NODE));
p->data=a;
p->next=q;
q=p;
ch=getchar();
}
q->next=NULL;
return(head);
}
main()
{
NODE *a;
a=create();
printf("output the list:");
a=a->next;
while(a!=NULL)
{
printf("%d",a->data);
a=a->next;
}
}
这个程序编译通过了,但是执行输出链表出错提示说“0x0040018f”指令引用内存不能为“read”~~~网上咨询了 经过修改 下面
#include<malloc.h>
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}NODE;
NODE *create()/*才用后插入方式建立单链表,并返回一个指向链表表头的指针,建立空表*/
{
NODE *head,*q,*p;
char ch;
int a;
head=(NODE*)malloc(sizeof(NODE));
q=head=NULL;
ch='*';
printf("/nInput the list:");
while(ch!='?') /*'ch'为是否建立新结点的标志,若'ch'为'?'则输入结束*/
{
scanf("%d",&a);
p=(NODE*)malloc(sizeof(NODE));
p->data=a;
p->next=q;
q=p;
ch=getchar();
}
//q->next=NULL;//这句话没有用,加上的话就把后边的节点都搞没了
return(q);//应该返回p,head指针没有变过
}
main()
{
NODE *a;
a=create();
printf("output the list:");
a=a->next;
while(a!=NULL)
{
printf("%d",a->data);
a=a->next;
}
}
改完可以运行了。哎,总算,搞定了,只是有些地方好像不怎么清晰。
又重新输一遍的原来的个代码 却可以运行
#include<malloc.h>
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}NODE;
NODE *create()
{
NODE *head,*p,*q;
char ch;
int a;
head=(NODE*)malloc(sizeof(NODE));
q=head;
ch='*';
printf("/nInput the list:");
while(ch!='?')
{
scanf("%d",&a);
p=(NODE*)malloc(sizeof(NODE));
p->data=a;
q->next=p;
q=p;
ch=getchar();
}
q->next=NULL;
return(head);
}
main()
{
NODE *a;
a=create();
printf("Output the list:");
a=a->next;
while(a!=NULL)
{
printf("%d",a->data);
a=a->next;
}
}
这里的q=head不需要为NULL,并且q->next=NULL应该为空的,return(head);返回头指针 这样理解应该没错的啊,但是还是没搞清楚最上面的那段代码哪儿不对了,而第二段代码的链表的最后一个的Next没有为空怎么说明那是链尾.......