当前位置:   article > 正文

leetcode206 反转单链表——单链表的逆置_单链表的逆置递归leecode

单链表的逆置递归leecode

题目描述:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表

leetcode链接:



力扣

思路一:链表的头插。由于改变了cur->next,因此需要记住cur->next的位置

图片:

代码:

  1. class Solution {
  2. public:
  3. ListNode* reverseList(ListNode* head) {
  4. if(head==NULL)
  5. {
  6. return NULL;
  7. }
  8. struct ListNode*cur=head;
  9. struct ListNode*newhead=NULL;
  10. struct ListNode*next=cur->next;
  11. while(cur)
  12. {
  13. cur->next=newhead;
  14. newhead=cur;
  15. cur=next;
  16. if(next)
  17. next=next->next;
  18. }
  19. return newhead;
  20. }
  21. };

 

思路二:指针的倒置,改变指针的方向反转单链表。

需要注意的是:对于空链表的处理,以及运行时next的处理。

图:

代码:

  1. class Solution {
  2. public:
  3. ListNode* reverseList(ListNode* head) {
  4. if(head==NULL)
  5. {
  6. return NULL;
  7. }
  8. struct ListNode*cur=head;//用于记住当前的位置
  9. struct ListNode*next=cur->next;//用于记住下一个结点的位置,否则倒转next的指向之后,无法找到下一个结点的位置
  10. struct ListNode*newhead=NULL;//NULL开始,因为原链表是以NULL结束的,用于返回逆置后的头节点
  11. while(cur)
  12. {
  13. cur->next=newhead;//倒转指针的指向
  14. //迭代
  15. newhead=cur;
  16. cur=next;
  17. if(next)//注意判断条件是while(cur),因此cur最终走到null结束,那么next=next->next会出现空指针的问题,需要判断
  18. next=next->next;
  19. }
  20. return newhead;
  21. }
  22. };

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号