温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言中字符串实现正序与逆序实例详解

发布时间:2020-10-25 00:58:40 来源:脚本之家 阅读:233 作者:lqh 栏目:编程语言

C语言中字符串实现逆序实例详解

字符串逆序和正序的实现代码:

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

#include <malloc.h>

#include <string.h>

/*定义*/

typedef struct node

{

 char c;

 struct node *llink,*rlink;

}stud;

/*建立链表*/

stud * creat(void)

{

 stud *p,*h,*s;

 char a;

 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=='\n')

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);

}

/*正序*/

void print1(stud *h)

{

 stud *p;

 p=h->rlink;

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

 while(p!=h)

 {

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

  p=p->rlink;

 }

 printf("\n");

}

/*逆序*/

void print2(stud *h)

{

 stud *p;

 p=h->llink;

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

 while(p!=h)

 {

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

  p=p->llink;

 }

 printf("\n");

}

/*释放*/

void free_stud(stud *h)

{

 stud *p,*q;

 p=h->llink;

 while(p!=h)

 {

  q=p;

  p=p->llink;

  free(q);

 }

 free(h);

}

/*主函数*/

int main()

{

 stud *head=NULL;

 head=creat();

 print1(head);

 print2(head);

 free_stud(head);

 return 0;

}

实现效果图:

C语言中字符串实现正序与逆序实例详解

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI