当前位置:   article > 正文

[数据结构]单链表逆置_数据结构单链表逆置算法代码实现

数据结构单链表逆置算法代码实现
  1. #include "stdafx.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. typedef struct tagListNode{
  5. int nData;
  6. struct tagListNode* s_pNext;
  7. }ListNode, *pListNode;
  8. void PrintList(pListNode head);
  9. pListNode ReverseList(pListNode head);
  10. int main()
  11. {
  12. //分配链表头结点
  13. ListNode *s_pHead;
  14. s_pHead = (ListNode*)malloc(sizeof(ListNode));
  15. s_pHead->s_pNext = NULL;
  16. s_pHead->nData = 0;
  17. //将[1,9]加入链表
  18. int i;
  19. ListNode *s_pNode1, *s_pNode2;
  20. s_pNode1 = s_pHead;
  21. for(i = 1; i < 10; i++)
  22. {
  23. s_pNode2 = (ListNode *)malloc(sizeof(ListNode));
  24. s_pNode2->nData = i;
  25. s_pNode2->s_pNext = NULL;
  26. s_pNode1->s_pNext = s_pNode2;
  27. s_pNode1 = s_pNode2;
  28. }
  29. //
  30. // 输出链表
  31. //
  32. PrintList(s_pHead);
  33. //
  34. // 逆序链表
  35. //
  36. s_pHead = ReverseList(s_pHead);
  37. //
  38. // 输出链表
  39. //
  40. PrintList(s_pHead);
  41. return 0;
  42. }
  43. pListNode ReverseList(pListNode s_pHead)
  44. {
  45. //
  46. // 入参检测
  47. //
  48. if(s_pHead == NULL || s_pHead->s_pNext == NULL)
  49. {
  50. return s_pHead;
  51. }
  52. ListNode *s_pTempNode = NULL,
  53. *s_pNode1 = s_pHead,
  54. *s_pNode2 = s_pHead->s_pNext;
  55. while(s_pNode2 != NULL)
  56. {
  57. s_pTempNode = s_pNode2->s_pNext;
  58. s_pNode2->s_pNext = s_pNode1;
  59. s_pNode1 = s_pNode2;
  60. s_pNode2 = s_pTempNode;
  61. }
  62. // 设置链表尾
  63. s_pHead->s_pNext = NULL;
  64. return s_pNode1;
  65. }
  66. void PrintList(pListNode s_pHead)
  67. {
  68. ListNode* p = s_pHead;
  69. while(p != NULL)
  70. {
  71. printf("%d ", p->nData);
  72. p = p->s_pNext;
  73. }
  74. printf("\n");
  75. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/680919
推荐阅读
相关标签
  

闽ICP备14008679号