牛客NC78反转链表(Java)(递归)

题目链接:牛客NC78反转链表
题目描述:在这里插入图片描述
递归到最底层,回溯时候将节点加到新链表后面

public class Solution {
    
    
    ListNode ans;
    ListNode temp;
    public ListNode ReverseList(ListNode head) {
    
    
    	//出口
        if(head==null){
    
    
            ans=new ListNode(0);
            temp=ans;
            return null;
        }
        //递归
        ReverseList(head.next);
        //拼接
        temp.next=head;
        temp=temp.next;
        temp.next=null;
        return ans.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/115116148