麻烦各位高手详细指点一下哈

#include <stdio.h>
#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct node)
struct node
{
int data;
struct node *next;
};

struct node *creat(void)
{
struct node *head=NULL;
struct node *p;
int c;

while((c=getchar())!=EOF)
{
p=(struct node*)malloc(LEN);
if(c=='\n')
continue;
p->data=(char)c;
p->next=NULL;

if(NULL==head)
{
head=p;
}
else
{
struct node *h=head;
while(h->next)
{
h=h->next;
}
h->next=p;
}
}

return(head);
}

struct node *Reversal(struct node *head)
{
struct node *p, *q, *t= NULL;
p = head;

while(q)
{
q=p->next;
p->next=t;
t=p;
p=q;
}
return t;
}
void print(struct node *head)
{
struct node *p;
printf("\tstrings after reverse:\n");
p=head;
if(head!=NULL)
do
{
printf("%c\n",p->data);
p=p->next;
}while(p!=NULL);
}
void main()
{
printf("\t Input the strings:");
struct node *r=creat();
r=Reversal(r);
print(r);
}

青春有我
浏览 118回答 2
2回答

森林海

#define NULL 0 //宏定义NULL为0#define LEN sizeof(struct node) //宏定义LEN为node结构体的字节数//定义结构体node,包含一个data成员变量,一个指向node型对象的指针成员变量struct node{int data;struct node *next;};//创建链表的函数,返回链表头指针struct node *creat(void){struct node *head=NULL; //定义头指针,赋值为空struct node *p; //定义一个节点的指针int c; ////从命令行读取字符串,构造链表while((c=getchar())!=EOF) //如果读取的字符不为结束字符{p=(struct node*)malloc(LEN);//开辟大小了Len的内存空间,赋值为pif(c=='\n') //如读取的字符为换行符,则进入下一次循环continue;p->data=(char)c; //p指向的对象的data为字符串cp->next=NULL;//p指向的对象的next指针指向空if(NULL==head) //如果头指针指向空,则将头指针指向p。(只会再构造第一个节点的时候判断成功){head=p;}else //否则{struct node *h=head; //定义一个指针h,指向head.while(h->next) //通过while循环将h指针移到最后一个节点{h=h->next;}h->next=p;//最后一个节点的next指向p,通过此方法将新节点接在链表的尾部}}return(head);//返回链表头指针}//这个函数有点问题吧,while(q),q一开始的时候就是NULL,那么就永远不会进入while循环//应该改成while(p)然后可以通过while循环将链表倒转,如果看不懂的话建议用笔在纸上画一个简短的链表,挨着走一遍就看得懂了。struct node *Reversal(struct node *head){struct node *p, *q, *t= NULL;p = head;while(q) //while(p){q=p->next;p->next=t;t=p;p=q;}return t; //走到这里,p和q都指向空了,t指向最后一个节点,然后返回t作为新的head}//输出函数,遍历打印每个节点void print(struct node *head){struct node *p;printf("\tstrings after reverse:\n");p=head;if(head!=NULL)do{printf("%c\n",p->data);p=p->next;}while(p!=NULL);}//main函数void main(){printf("\t Input the strings:");struct node *r=creat(); //构造链表r=Reversal(r);//翻转链表print(r);//遍历输出链表}&nbsp;

猛跑小猪

#include <stdio.h>#include <malloc.h>#define NULL 0#define LEN sizeof(struct node)struct node{int data;struct node *next;};node *creat(void){node *head=NULL;node *p;int c;while((c=getchar())!='\n'){p=(node*)malloc(LEN);if(c=='\n')continue;p->data=(char)c;p->next=NULL;if(NULL==head){head=p;}else{node *h=head;while(h->next){h=h->next;}h->next=p;}}return(head);}node *Reversal( node *head){node *p, *q, *t= NULL;p = head;while(q){q=p->next;p->next=t;t=p;p=q;}return t;}void print( node *head){node *p;printf("strings after reverse:");p=head;if(head!=NULL)do{printf("%c",p->data);p=p->next;}while(p!=NULL);printf("\n");}void main(){printf("Input the strings:");node *r=creat();r=Reversal(r);print(r);}
打开App,查看更多内容
随时随地看视频慕课网APP