题解 | #反转链表#

反转链表

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

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

递归法:一开始对反转的操作理解不了,可能是太菜了,然后想了一个自己能容易理解的方式(大佬勿喷)

// 链表:1 -> 2 -> null
node = ReverseList(1.next); // 1.next = 2, node = 2
1.next.next = 1;
1.next = null;
return 2;
// 此时链表为 2 -> 1 -> null

注意理解递归中的递归公式,以及边界条件。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务