1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > c语言单链表存储字符串 用链表的形式存储一个字符串 按正序和逆序输出字符串(数据结

c语言单链表存储字符串 用链表的形式存储一个字符串 按正序和逆序输出字符串(数据结

时间:2020-02-07 12:47:28

相关推荐

c语言单链表存储字符串 用链表的形式存储一个字符串 按正序和逆序输出字符串(数据结

满意答案

这个字符串的输出,考虑到有正序和逆序,采用链表,可以考虑用双链表。这样输出效率会比较高。

建议用循环双链表(带头结点),方便程序处理,简化操作流程,步骤明晰,便于调试。

关键函数可分为:

1,结构的定义

2,初始化链表

3,输出(正序,逆序)

4,释放链表

5,主函数

以下C语言代码在VC6.0中编译通过:

#include

#include

#include

#include

#include

/*定义*/

typedefstructnode

{

charc;

structnode*llink,*rlink;

}stud;

/*建立链表*/

stud*creat(void)

{

stud*p,*h,*s;

chara;

if((h=(stud*)malloc(sizeof(stud)))==NULL)

{

printf("不能分配内存空间!");

exit(0);

}

h->c=0;

h->llink=NULL;

h->rlink=NULL;

p=h;

while(1)

{

a=getchar();

if(a=='

')

break;

if((s=(stud*)malloc(sizeof(stud)))==NULL)

{

printf("不能分配内存空间!");

exit(0);

}

p->rlink=s;

s->c=a;

s->llink=p;

s->rlink=NULL;

p=s;

}

h->llink=s;

p->rlink=h;

return(h);

}

/*正序*/

voidprint1(stud*h)

{

stud*p;

p=h->rlink;

printf("字符串(正序):");

while(p!=h)

{

printf("%c",p->c);

p=p->rlink;

}

printf("

");

}

/*逆序*/

voidprint2(stud*h)

{

stud*p;

p=h->llink;

printf("字符串(逆序):");

while(p!=h)

{

printf("%c",p->c);

p=p->llink;

}

printf("

");

}

/*释放*/

voidfree_stud(stud*h)

{

stud*p,*q;

p=h->llink;

while(p!=h)

{

q=p;

p=p->llink;

free(q);

}

free(h);

}

/*主函数*/

intmain()

{

stud*head=NULL;

head=creat();

print1(head);

print2(head);

free_stud(head);

return0;

}

00分享举报

c语言单链表存储字符串 用链表的形式存储一个字符串按正序和逆序输出字符串(数据结构考试)...

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。