剑指offer之反转链表

举报
chenyu 发表于 2021/07/27 00:22:18 2021/07/27
【摘要】 1 问题 反转链表,比如0->1->2->3反转后变成了3->2->1->0                 2 分析 搞3个指针,初始化一个指针,让头结点指向这里,然后另外一个指针初始化为NULL,然后让第一个节点指向这里,然后头结点依次...

1 问题

反转链表,比如0->1->2->3反转后变成了3->2->1->0

 

 

 

 

 

 

 

 

2 分析

搞3个指针,初始化一个指针,让头结点指向这里,然后另外一个指针初始化为NULL,然后让第一个节点指向这里,然后头结点依次向右移,这个初始化为NULL的指针也向右移动,然后最后当头结点的next指向NULL的时候,我们直接返回这个节点就行了。

 

 

 

 

 

3 代码实现


  
  1. #include <stdio.h>
  2. typedef struct Node
  3. {
  4. int val;
  5. struct Node *next;
  6. } Node;
  7. /*
  8. *print list
  9. */
  10. void print_list(Node *head)
  11. {
  12. if (head == NULL)
  13. {
  14. printf("head is NULL\n");
  15. return;
  16. }
  17. Node *p = head;
  18. while (p != NULL)
  19. {
  20. printf("value is %d\n", p->val);
  21. p = p->next;
  22. }
  23. }
  24. /*
  25. *reverse list
  26. */
  27. struct Node* reverse(Node *head)
  28. {
  29. if (head == NULL)
  30. {
  31. printf("reverse head is NULL\n");
  32. return NULL;
  33. }
  34. Node *end = NULL;
  35. Node *p = head;
  36. Node *start = NULL;
  37. while (p != NULL)
  38. {
  39. //next node
  40. Node *next = p->next;
  41. //If next is NULL, we will store p, we will return p in the end;
  42. if (next == NULL)
  43. {
  44. end = p;
  45. }
  46. p->next = start;
  47. start = p;
  48. p = next;
  49. }
  50. return end;
  51. }
  52. int main()
  53. {
  54. //0->1->2->3;
  55. Node head, node1, node2, node3;
  56. head.val = 0;
  57. head.next = &node1;
  58. node1.val = 1;
  59. node1.next = &node2;
  60. node2.val = 2;
  61. node2.next = &node3;
  62. node3.val = 3;
  63. node3.next = NULL;
  64. print_list(&head);
  65. printf("list will reverse\n");
  66. Node *hello = reverse(&head);
  67. print_list(hello);
  68. return 0;
  69. }

 

 

 

 

 

4 运行结果


  
  1. value is 0
  2. value is 1
  3. value is 2
  4. value is 3
  5. list will reverse
  6. value is 3
  7. value is 2
  8. value is 1
  9. value is 0

 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/89856077

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。