206.反转链表

2022-01-10 16:33:29 浏览数 (1)

算法

代码语言:javascript复制
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //递归解决
        ListNode pre = null;
        return reverse(pre, head);
    }
    public static ListNode reverse(ListNode pre, ListNode head){
        //1.递归的终止条件
        if(head == null){
            return pre;
        }
        //2.当前递归的操作   
        ListNode temp = null;
        temp = head.next;
        head.next = pre;
        pre = head;
        head = temp;
        //3.返回给上一级递归的数据
        return reverse(pre, head);
    }
}

本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名,转载请标明出处 最后编辑时间为: 2021/12/14 12:58

0 人点赞