首页 > 其他 > 详细

leetcode 206反转链表

时间:2021-08-30 09:13:43      阅读:16      评论:0      收藏:0      [点我收藏+]

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
技术分享图片
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

技术分享图片
输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]
提示:

链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

尾递归:比普通的递归好,具体自行搜索。

lic class seqecStack {
    public ListNode reverseList(ListNode head) {
        return reverse(head,null);
    }
    public ListNode reverse(ListNode head,ListNode tail)
    {
        if(head==null)
            return tail;
        ListNode next= head.next;
        head.next=tail;

        return reverse(next,head);
    }

非尾递归

  public ListNode reverseList(ListNode head) {
       if(head==null||head.next==null)
       {
           return head;
       }
       ListNode next=head.next;
       ListNode newHead=reverseList(next);

       next.next=head;
       head.next=null;
       return newHead;
    }

leetcode 206反转链表

原文:https://www.cnblogs.com/AI-Creator/p/15196446.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!