【数据结构】递归实现链表逆序

前端之家收集整理的这篇文章主要介绍了【数据结构】递归实现链表逆序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

关于本篇文章,先参见本人之前的一篇博客,与之相关:

http://blog.csdn.net/kuzuozhou/article/details/7451289

另外,参考:

http://blog.csdn.net/ssjhust123/article/details/7754103

  1. #include<stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node//节点存放一个数据和指向下一个节点的指针
  5. {
  6. int data;
  7. struct node* pnext;
  8. } Node;
  9.  
  10. Node *link_create()//链表创建
  11. {
  12. int item;
  13. Node *head = NULL;
  14. do
  15. {
  16. Node *p;
  17. scanf("%d",&item);
  18. p = (Node *)malloc(sizeof(Node));
  19. if(p == NULL)
  20. {
  21. printf("memory applied Failed\n");
  22. break;
  23. }
  24. p->data = item;
  25. p->pnext = head;
  26. head = p;
  27. }while(getchar() != '\n');
  28. return head;
  29. }
  30.  
  31. void link_show(Node *head)
  32. {
  33. Node* p;
  34. p=head;
  35. while(p != NULL)
  36. {
  37. printf("%d ",p->data);
  38. p = p->pnext;
  39. }
  40. printf("\n");
  41. }
  42.  
  43. void link_destroy(Node *head)
  44. {
  45. Node* p;
  46. Node* tmp;
  47. p=head;
  48. while(p != NULL)
  49. {
  50. tmp = p->pnext;
  51. free(p);
  52. p = tmp;
  53. }
  54. }
  55.  
  56. //Node *link_reverse(Node *head)
  57. //{
  58. // Node *pre,*cur,*next;
  59. // /*head->pnext =NULL;*/
  60. //
  61. // pre = head;
  62. // cur = pre->pnext;
  63. // next = cur->pnext;
  64. // head->pnext =NULL;//第一次的pre,cur,next
  65. //
  66. // if(next == NULL)//链表只有两个节点,如果没有此语句,当链表确实只有两个节点时,就会发生错误
  67. // {
  68. // cur->pnext = pre;
  69. // head = cur;
  70. // return head;
  71. // }
  72. //
  73. // while(next->pnext != NULL)
  74. // {
  75. // cur->pnext = pre;//修改指针,每次循环修改一次
  76. //
  77. // pre = cur;
  78. // cur = next;
  79. // next = next->pnext;
  80. // }//循环终止时,next->pnext == NULL
  81. // cur->pnext = pre;
  82. // next->pnext = cur;
  83. // head = next;
  84. // return head;
  85. //
  86. //}
  87.  
  88. void link_reverse(Node **headRef)//递归来实现链表逆序,相比上面注释的部分实现,显得相当简洁
  89. {
  90. Node *first,*rest;
  91. if(*headRef == NULL)
  92. return;
  93. first = *headRef;
  94. rest = first->pnext;
  95. if(rest == NULL)
  96. return;
  97. link_reverse(&rest);
  98. first->pnext->pnext = first;
  99. first->pnext = NULL;
  100. *headRef = rest;
  101. }
  102.  
  103.  
  104. int main()
  105. {
  106. Node *new_head=NULL;
  107. Node *head = link_create();
  108. link_show(head);
  109. //new_head = link_reverse(head);
  110. link_reverse(&head);
  111. link_show(new_head);
  112. link_destroy(new_head);
  113.  
  114. //system("pause");
  115. return 0;
  116. }
  117.  

猜你在找的数据结构相关文章