当前位置:   article > 正文

LeetCode206: 反转链表_leetcode 反转链表 leetcode

leetcode 反转链表 leetcode

反转一个单链表

进阶:

链表可以迭代或递归地反转。你能否两个都实现一遍?

思路:

https://blog.csdn.net/fx677588/article/details/72357389

1. 首先是迭代的反转链表


方式如上图所示, 

2. 利用递归

代码:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. // ListNode pre = null;
  12. // ListNode next = null;
  13. // while(head!=null){
  14. // next = head.next;
  15. // head.next = pre;
  16. // pre = head;
  17. // head = next;
  18. // }
  19. // return pre;
  20. if(head==null || head.next==null){
  21. return head;
  22. }
  23. ListNode h = reverseList(head.next);
  24. head.next.next = head;
  25. head.next = null;
  26. return h;
  27. }
  28. }

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

闽ICP备14008679号