反转链表前N个节点

反转链表前N个节点,并返回反转后的链表

ListNode结构如下

    public class ListNode {
    
    
        int val;
        ListNode next;
        ListNode(int x) {
    
     val = x; }
    }
class Solution {
    
    
    //后继节点
    ListNode successor = null;
    public ListNode reverseN(ListNode head, int n){
    
    
        if (head == null || head.next == null) return head;
        if (n == 1){
    
    
            successor = head.next;
            return head;
        }
        ListNode last = reverseN(head.next, n-1);
        head.next.next = head;
        head.next = successor;
        return last;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40660894/article/details/113476707