2 回答

TA贡献2011条经验 获得超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的内存空间,赋值为p
if(c=='\n') //如读取的字符为换行符,则进入下一次循环
continue;
p->data=(char)c; //p指向的对象的data为字符串c
p->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);//遍历输出链表
}

TA贡献1858条经验 获得超8个赞
#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);
}
- 2 回答
- 0 关注
- 117 浏览
添加回答
举报