递归法完成数组反转

反转链表

http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca

public ListNode ReverseList(ListNode head) {
    // 若链表元素小于 2 时,无需反转,直接返回
    if (head == null || head.next == null) {
        return head;
    }
    // 创建一个新节点,用于作为反转链表的头节点,并进行递归操作
    ListNode newHead = ReverseList(head.next);
    // 由于之前 if 语句已经判断了链表元素小于 2 的情况,无需担心 head.next.next 会发生空指针
    // 令 head.next 指向 head,完成一次反转
    head.next.next = head;
    // head 指向空,用于作为尾节点
    head.next = null;
    // 返回头节点
    return newHead;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务