2 回答

TA貢獻(xiàn)2011條經(jīng)驗 獲得超2個贊
#define NULL 0 //宏定義NULL為0
#define LEN sizeof(struct node) //宏定義LEN為node結(jié)構(gòu)體的字節(jié)數(shù)
//定義結(jié)構(gòu)體node,包含一個data成員變量,一個指向node型對象的指針成員變量
struct node
{
int data;
struct node *next;
};
//創(chuàng)建鏈表的函數(shù),返回鏈表頭指針
struct node *creat(void)
{
struct node *head=NULL; //定義頭指針,賦值為空
struct node *p; //定義一個節(jié)點的指針
int c; //
//從命令行讀取字符串,構(gòu)造鏈表
while((c=getchar())!=EOF) //如果讀取的字符不為結(jié)束字符
{
p=(struct node*)malloc(LEN);//開辟大小了Len的內(nèi)存空間,賦值為p
if(c=='\n') //如讀取的字符為換行符,則進(jìn)入下一次循環(huán)
continue;
p->data=(char)c; //p指向的對象的data為字符串c
p->next=NULL;//p指向的對象的next指針指向空
if(NULL==head) //如果頭指針指向空,則將頭指針指向p。(只會再構(gòu)造第一個節(jié)點的時候判斷成功)
{
head=p;
}
else //否則
{
struct node *h=head; //定義一個指針h,指向head.
while(h->next) //通過while循環(huán)將h指針移到最后一個節(jié)點
{
h=h->next;
}
h->next=p;//最后一個節(jié)點的next指向p,通過此方法將新節(jié)點接在鏈表的尾部
}
}
return(head);//返回鏈表頭指針
}
//這個函數(shù)有點問題吧,while(q),q一開始的時候就是NULL,那么就永遠(yuǎn)不會進(jìn)入while循環(huán)
//應(yīng)該改成while(p)然后可以通過while循環(huán)將鏈表倒轉(zhuǎn),如果看不懂的話建議用筆在紙上畫一個簡短的鏈表,挨著走一遍就看得懂了。
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指向最后一個節(jié)點,然后返回t作為新的head
}
//輸出函數(shù),遍歷打印每個節(jié)點
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函數(shù)
void main()
{
printf("\t Input the strings:");
struct node *r=creat(); //構(gòu)造鏈表
r=Reversal(r);//翻轉(zhuǎn)鏈表
print(r);//遍歷輸出鏈表
}

TA貢獻(xiàn)1858條經(jīng)驗 獲得超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 關(guān)注
- 114 瀏覽
添加回答
舉報