javaleetcode206. 反转链表

Posted 季.夏.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaleetcode206. 反转链表相关的知识,希望对你有一定的参考价值。

问题描述

leetcode106. 反转链表


题目分析:

对于递归算法,最重要的就是明确递归函数的定义。具体来说,我们的 reverseList 函数定义是这样的:
输入一个节点 head,将以 head 为起点的链表反转,并返回反转之后的头结点。
明白了函数的定义,再来看这个问题。比如说我们想反转这个链表:

那么输入 reverse(head) 后,会在进行递归:
ListNode last = reverseList(head.next);


接下来:
head.next.next=head;
head.next = null;
return last;


代码实现:

class Solution 
    public ListNode reverseList(ListNode head) 
        if(head==null) return head;
        if(head.next==null) return head;
        ListNode last= reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return last;
    


解法二:

class Solution 
    public ListNode reverseList(ListNode head) 
        ListNode cur=head;
        ListNode prev=null;
        while(cur!=null)
            ListNode next=cur.next;
            cur.next=prev;
            prev=cur;
            cur=next;
        
        return prev;
    

以上是关于javaleetcode206. 反转链表的主要内容,如果未能解决你的问题,请参考以下文章

算法热门:反转单链表(LeetCode 206)解法二

leetcode 206. 反转链表(Reverse Linked List)

LeetCode206.反转链表

反转链表递归迭代

反转链表递归迭代

反转链表递归迭代