链表第2天

71 阅读1分钟

剑指 Offer 24. 反转链表

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

92. 反转链表 II

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(left == 1)
            return reverseTo(head, right);
        else
            head.next = reverseBetween(head.next, left - 1, right - 1);
        return head;
    }

    public ListNode reverseTo(ListNode head, int right){
        if(right == 1)
            return head;
        ListNode res = reverseTo(head.next, right - 1);
        
        ListNode next = head.next;
        head.next = next.next;
        next.next = head;

        return res;
    }
}