leetcode 206反转链表

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

image
输入: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;
    }
posted @ 2021-08-28 11:48  LiangLiangAA  阅读(19)  评论(0编辑  收藏  举报
theme: { name: 'geek', avatar: '', headerBackground: '' // ... },