鱼C论坛

 找回密码
 立即注册
查看: 3684|回复: 5

[技术交流] 线性链表逆置c语言算法

[复制链接]
发表于 2011-8-20 20:11:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include<stdio.h>
  2. #include<malloc.h>

  3. struct node
  4. {
  5. char data;
  6. struct node * next;
  7. };

  8. struct node * creat(void);
  9. void InverseList(struct node * head);
  10. void print(struct node * head);

  11. int main(void)
  12. {
  13. struct node * head = NULL;

  14. head = creat();
  15. print(head);
  16. InverseList(head);
  17. print(head);
  18. system("pause");
  19. }

  20. struct node * creat(void)
  21. {
  22. struct node * head = (struct node *)malloc(sizeof(struct node));
  23. struct node * tail = head;
  24. tail->next = NULL;

  25. char c;
  26. int flag = 1;

  27. printf("You want to invert squence: ");

  28. while(flag)
  29. {
  30. c = getchar();
  31. if(c != '\n')
  32. {
  33. struct node * recieve = (struct node *)malloc(sizeof(struct node));

  34. recieve->data = c;

  35. tail->next = recieve;
  36. recieve->next = NULL;
  37. tail = recieve;
  38. }
  39. else
  40. {
  41. flag = 0;
  42. tail->next = NULL;
  43. }
  44. }
  45. return head;
  46. }

  47. void InverseList(struct node * head)
  48. {
  49. struct node * p = head->next; // 定义两个指针指向第一个元素
  50. struct node * q = head->next;
  51. q = q->next; //q保存下一个元素的地址
  52. p->next = NULL; //断开第一个和第二个元素的指针
  53. p = q; //p指向下一个元素 p和q同时指在第二个元素

  54. while(p != NULL)
  55. {
  56. q = q->next; //q保存下一个元素的地址
  57. p->next = head->next; //插入p当前指向的元素在当前头指针之后,也就是第一个位置插入
  58. head->next = p; //和上一句一起完成插入
  59. p = q; //p和q再次同时指向同一个元素
  60. }
  61. }

  62. void print(struct node * head)
  63. {
  64. struct node * p = head->next;

  65. while(p)
  66. {
  67. printf("%c",p->data);
  68. p = p->next;
  69. }
  70. printf("\n");
  71. }
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2013-7-1 23:18:40 | 显示全部楼层
看看学习学习
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2013-7-2 17:51:39 | 显示全部楼层
很难,看不懂
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2013-7-4 13:35:22 | 显示全部楼层
支持鱼C!支持论坛!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2013-7-19 08:57:40 | 显示全部楼层
谢谢你的测试
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2013-7-23 21:40:21 | 显示全部楼层
先标记, 以后有空再看看
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 14:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表